ArrayList中搜索.NET [英] ArrayList Search .net

查看:103
本文介绍了ArrayList中搜索.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是存储在我的数组列表中的数据的格式。

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

A-Amsterdam
B- Brussels
C-Canada

如此等等。
我婉通过传递只是前几个字符,直到搜索我的数组列表 -
所以,如果我有像AA-测试,然后我想通过只是'AA',以检查它是否存在与否。

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

推荐答案

您可以通过创建自己的IComparer并将其传递到二分查找解决这个问题:

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());

这篇关于ArrayList中搜索.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆