[Development story] The third time, implement the collection class sort custom sort

Source: Internet
Author: User

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:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.