Sorting collection elements is a frequent occurrence, and in fact most of the collection types implement the Sort method by default, sorting operations on their elements. For example, the sort method for the List<t> collection is:
public void Sort();
public void Sort(Comparison<T> comparison);
public void Sort(IComparer<T> comparer);
public void Sort(int index,int count,IComparer<T> comparer);
In the sort usage, four sorts are the same, and the only difference is that in most cases, the ordering requirement determines that we cannot fully satisfy the default sort, because the framework simply does not know the purpose of the "You" sort, for example:
BookStore bs = new BookStore
{
Books = new List<Book> {
new Book{ID = 1,Name="你必须知道 的.NET",Price=69,PublishDate=DateTime.Parse("2008-3-30")},
new Book{ID = 2,Name="Silverlight完美征 程",Price=75,PublishDate=DateTime.Parse("2009-4-30")},
new Book{ID =3,Name="博客园精华 集",Price=72,PublishDate=DateTime.Parse("2009-5-3")}
}
};
Implementing a custom sorting algorithm
If you need to sort the bookstore's bibliography, at least we can sort by book title, book Price, and publication date in our small example, so the. NET Framework is designed to provide a good extension of sort, In general, we need to implement custom comparison and comparer, such as:
// Release : code01,2009/04/12
// Author : Anytao,http://www.anytao.com
// List : Protram.cs
//02 Sort by custom comparison
bs.Books.Sort((a,b) => { return a.Price.CompareTo(b.Price); });
foreach (var item in bs.Books)
{
Console.WriteLine(string.Format("{0}:{1}, {2}",item.Name,item.Price,item.PublishDate.ToString()));
}
You see how simple it is to implement a custom comparison with a lambda expression:
bs.Books.Sort((a,b) => { return a.Price.CompareTo (b.Price); });
The results of the output are: