Condividi tramite


Sorting a List in C#

I often receive emails from developers asking for help with their development conundrums. One of the common questions I get asked, especially from someone learning C# and writing their first app, is how to sort a list of items.

It's quite simple actually; there are 2 ways you can sort a list, and both have their own purpose as defined below.

Using the first method you can sort a list in place, i.e. without having to create a copy of the list. E.g. if you had a list of an object which contained a date and you would like to sort the list in chronological order, you can do something like the following:

MyList.Sort((x, y) => x.OrderDate.CompareTo(y.OrderDate));

The second method does not sort the list in place, but rather returns a sorted copy of the original list.

 

To read more, go to https://paraswadehra.blogspot.com/2014/01/sorting-list-in-c-sharp.html

 

Regards,
Paras Wadehra
Nokia Developer Ambassador
INETA Community Champion
Twitter: @ParasWadehra
FB Group: https://FB.com/MSFTDev
Great WP Apps

Comments

  • Anonymous
    February 24, 2014
    Paras, Thanks for this. I'm bookmarking this to show newbies when they ask me this question.  One comment, you listed the second method ( a copy of the newly sorted list) on your personal blog, but it got omitted here for some reason. Not sure if that was planned or not.

  • Anonymous
    November 23, 2014
    Hi paras. Thanks for the info...How can you sort without using the sort function according to date time