2014-01-20 100 views
0

如何從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")); 
+1

一樣做任何其他語言 –

+1

二進制搜索除非你排序列表,二進制搜索是不是要去工作。 – spender

+1

http://msdn.microsoft.com/en-us/library/w4e7fxsh(v=vs.110).aspx – OopsUser

回答

0

看來你正在尋找的是一個Find

IDDesc result = list.Find(item => item.Description.Contains("C")); 
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; 
+0

請告訴我你將如何做我想做的事情。 – user2330678

+1

伴侶,他問BinarySearch,你給他一個線性的,這顯然不會幫助他或將有效的巨大數據。 –

+1

他無法對「包含」進行二分搜索。 –

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; 
     } 
    } 

然後你就可以創建一個具有二分查找這看起來像這樣的事情的方法:

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; 
    }