Random programming things I'd want to remember

Sunday, March 25, 2012

How to order a collection by a custom property

Suppose you have the following code:

public class TestItem { public string Name { get; set; } public int Count { get; set; } } public partial class MainPage : PhoneApplicationPage { // Constructor public MainPage() { InitializeComponent(); List<TestItem> li = new List<TestItem>(); TestItem a = new TestItem { Name = "First name", Count = 1 }; TestItem b = new TestItem { Name = "Second name", Count = 3 }; TestItem c = new TestItem { Name = "Third name", Count = 2 }; //But how do I order the items in the collection by Count property? listBox1.DataContext = li; } }
If I want to order the collection before binding it to the listbox, how do you do that? This is how:

li.Sort((a, b) => a.SortingParam.CompareTo(b.SortingParam));

No comments: