How can I sort List<T> based on properties of T?

Ujwala picture Ujwala · Mar 3, 2009 · Viewed 16.4k times · Source

My Code looks like this :

Collection<NameValueCollection> optionInfoCollection = ....
List<NameValueCollection> optionInfoList = new List<NameValueCollection>();
optionInfoList = optionInfoCollection.ToList();

if(_isAlphabeticalSoting)
   Sort optionInfoList

I tried optionInfoList.Sort() but it is not working.

Answer

m-sharp picture m-sharp · Mar 3, 2009

Using the sort method and lambda expressions, it is really easy.

myList.Sort((a, b) => String.Compare(a.Name, b.Name))

The above example shows how to sort by the Name property of your object type, assuming Name is of type string.