Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList Search .net

Following is the format of the data stored in my arraylist.

A-Amsterdam
B- Brussels
C-Canada

so and so forth. I wan to search my array list by passing just the first few characters till '-' So if i have something like AA-Test then i want to pass just 'AA' to check if it exists or not.

I know that i can use contains or binarysearch but it does not serve my purpose as they both compare objects.

Any suggestions?? thanks

like image 470
jsp Avatar asked Mar 20 '26 17:03

jsp


1 Answers

You can solve this by creating your own IComparer and passing it into BinarySearch:

public class StartsWithComparer : IComparer
{
    public int Compare(Object x, Object y)
    {
        String left = x as String;
        String right = y as String;

        if (ReferenceEquals(left, right))
        {
            return 0;
        }

        if (ReferenceEquals(left, null))
        {
            return -1;
        }

        if (ReferenceEquals(right, null))
        {
            return 1;
        }

        return (x.StartsWith(y) || y.StartsWith(x)) ? 0 : x.CompareTo(y);
    }
}

Later...

myArrayList.Sort()
myArrayList.BinarySearch("AA", new StartsWithComparer());
like image 53
codekaizen Avatar answered Mar 22 '26 08:03

codekaizen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!