搜索对象列表

时间:2014-01-20 18:29:12

标签: c# .net

如何使用项目的属性从C#中的对象列表中搜索项目?

public Class IDDesc
{
    public int ID {get;set;}
    public string Description {get; set;}
}

List<IDDesc>list = new List<IDDesc>();
int index=list.BinarySearch(list.Description.Contains("C"));

3 个答案:

答案 0 :(得分:3)

您确定了解二进制搜索是什么吗?

来自wiki

  

在计算机科学中,二进制搜索或半间隔搜索算法在按键排序的数组中找到指定输入值(搜索“键”)的位置价值

您没有已排序的集合,并且您没有找到密钥。您正在寻找符合x.Description.Contains("C")条件的所有商品。

二进制搜索不是一种方法。

您可以使用LINQ标准线性搜索获得所需内容:

int index = list.Select((x, i) => new { Value = x, Index = i })
                .First(x => x.Value.Description.Contains("C"))
                .Index;

答案 1 :(得分:0)

您正在寻找的是Find

IDDesc result = list.Find(item => item.Description.Contains("C"));

答案 2 :(得分:0)

首先,您应该在对象中实现IComparable接口,如例:

    public class IDDesc : IComparable<IDDesc>
    {    
        public int ID { get; set; }
        public string Description { get; set; }

        public int CompareTo(IDDesc other)
        {
        //     A value that indicates the relative order of the objects being compared.
        //     The return value has the following meanings: Value Meaning Less than zero
        //     This object is less than the other parameter.Zero This object is equal to
        //     other. Greater than zero This object is greater than other.
             int ret = -1;
             if (this.ID > other.ID)
                 ret = 1;
             else if (this.ID == other.ID)
                 ret = 0;

             return ret;
        }
    }

然后你可以创建一个BinarySearch的方法,它看起来像这样:

    public IDDesc GetIDDescByID(int ID)
    {
        IDDesc toFind = new IDDesc();
        toFind.ID = ID;
        //List Items must be sorted!
        list.Sort();
        int foundIndex = list.BinarySearch(toFind);
        if (foundIndex > -1)
            toFind = list[foundIndex];

        return toFind;
    }