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.

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.

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: Logo

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s