List.Find() and List.Sort() basic use

List is a very useful generic class that .NET provide.
There are two things you probably wants to do with a list. Find an item and sort items.
List是.NET提供的一個很有用的泛型類別.你大概會用List去做兩件事,找特定的項目和排序.

If you want to find an item, you can use anonymous delegate.
For example, You have a list of object, whose class has an index property.
I want to find an object with a certain index.
如果你想找出一個特定的項目,你可以用匿名委派.下面有一個例子,你有一列表的物件,其類別包含一個索引屬性.你想找出某個索引的項目.

List l_itemList = new List();
int l_index = someIndex; //maybe 10
MyClass l_itemFound = l_itemList.Find(delegate(Myclass instance)
{
if(instance != null)
{
return instance.index == l_index;
}
return false;
});

This will give you the instance whose index is someIndex, default vale for MyClass otherwise.
這樣就能找出對應的物件,如果找不到就會傳回該類別的預設值.

If you are sorting a List of primitive .NET datatypes, you just have to do List.Sort(). For user class, you have to implement IComparable interface, which only have one method CompareTo(object obj).
如果你的列表是.NET原生資料型態, 你只要直接調用List.Sort()就可完成排序. 其他使用者自訂類別,你就要實作IComparable介面,這個介面只有一個方法 CompareTo(object obj)

private class MyClass : IComparable
{
   public int index;
   public int CompareTo(Object obj)
   {
      MyClass l_comparer = obj as MyClass;
      return this.index.CompareTo(l_comparer.index);
   }
}

I use the Int32.CompareTo() to do the job since I am comparing index. You can create your own CompareTo(). The return value should be as follow.
Caller is smaller than obj, return < 0. Caller is equal to obj, return 0. Caller is larger than obj, return > 0.
我用Int32.CompareTo()去完成,因為我在比較的是類別的索引而已.你可以實作你需要的CompareTo().其回傳的值應該如下.
呼叫者小於參數,回傳小於零的值.
呼叫者等於參數,回傳零.
呼叫者大於參數,回傳大於零的值.

Delegate version

l_itemList.Sort(delegate(MyClass p1, MyClass p2)

{

return p1.Attr.CompareTo(p2.Attr);

});

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s