Sorting set elements is a common occurrence. In fact, most set types implement the Sort method by default to Sort their elements. For example, the Sort methods of the List <T> set include:
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 terms of sorting usage, the four Sort types are similar. The only difference is that in most cases, the sorting requirements determine that we cannot fully satisfy the default sorting conditions, because the Framework does not know the purpose of "you" sorting, for example:
BookStore bs = new BookStore {Books = new List <Book> {new Book {ID = 1, Name = "you must know. NET ", Price = 69, PublishDate = DateTime. parse ("2008-3-30")}, new Book {ID = 2, Name = "Silverlight perfect journey", Price = 75, PublishDate = DateTime. parse ("2009-4-30")}, new Book {ID = 3, Name = "", Price = 72, PublishDate = DateTime. parse ("2009-5-3 ")}}};Implement a custom Sorting Algorithm
If you want to sort the bibliography of a bookstore, you can sort the bibliography at least by name, price, and publication date in our small example. NET Framework is designed to provide excellent extensions for Sort. Generally, we need to implement custom comparison and comparer, for example:
// 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 can see how simple it is to use Lambda expressions to implement a Custom Comparison:
bs.Books.Sort((a, b) => { return a.Price.CompareTo(b.Price); });
The output result is:
If we implement Custom Comparison sorted by publication date, it should be like this:
bs.Books.Sort((a, b) => { return a.PublishDate.CompareTo(b.PublishDate); });
The sorting result is as expected:
Comparison implemented using Lamdba expressions becomes very simple and elegant. We will resolve the Lamdba expression to an Anonymous Method in regression complexity ):
// Release : code01, 2009/04/12 // Author : Anytao, http://www.anytao.com // List : Protram.cs//03 Sort by custom comparison: Anonymous Methodbs.Books.Sort(delegate(Book a, Book b){ return a.Price.CompareTo(b.Price);});
If you are still confused about the anonymous method, we will return to the original implementation of Custom Comparison:
// Release : code01, 2009/04/12 // Author : Anytao, http://www.anytao.com // List : BookComparison.cspublic class BookComparison : IComparer<Book>{ public int Compare(Book x, Book y) { return x.Price.CompareTo(y.Price); }}
Use BookComparison for comparison,
//04 Sort by custom comparison: BookComparisonbs.Books.Sort(new BookComparison().Compare);
The output result is the same as bs. Books. Sort (a, B) =>{ return a. Price. CompareTo (B. Price.
More control can be implemented in a custom way. For example, we reconstruct BookComparison:
// Release : code01, 2009/04/12 // Author : Anytao, http://www.anytao.com // List : BookComparison.cspublic class BookComparison : IComparer<Book>{ private ComparisonType type; public BookComparison(ComparisonType type) { this.type = type; } public int Compare(Book x, Book y) { switch (this.type) { case ComparisonType.Price: return x.Price.CompareTo(y.Price); break; case ComparisonType.PublishDate: return x.PublishDate.CompareTo(y.PublishDate); break; default: break; } return 0; }}
Add a ComparisonType structure. The Comparison method is determined during BookComparson initialization:
//04 Sort by custom comparison: BookComparisonbs.Books.Sort(new BookComparison(ComparisonType.PublishDate).Compare);
Conclusion
Custom Comparison provides a good extension mechanism for better Sort control. In our practical applications, for specific applications such as BookStore, I recommend using OrderBy of LINQ, for example:
//05 Sort by Linqvar list = from c in bs.Books orderby c.PublishDate ascending select c;foreach (var item in list){ Console.WriteLine(string.Format("{0}:{1}, {2}", item.Name, item.Price, item.PublishDate.ToString()));}
The orderby clause can select any sorting condition, and the ascending or descending can control the ascending and descending order.
Where to go, view the self-evaluation.