Sorting a C# List by multiple columns

c#, combobox, list, sorting, wpf

Solution

The reason is because `OrderBy` does not transform the object it is called on, instead it returns a new result. You should use it like this:

samples = samples.OrderBy(a => a.SortOrder).ThenBy(a => a.Description).ToList();

This is the way the `OrderBy` function works. Why would you need it to work the other way, especially for just a few extra characters.

You could make it work, by creating your own extension methods that do the same thing except work on the reference to the object rather than creating a new result, but this is not worth the trouble at all.

If you need something though, you could just wrap the LINQ in an extension method like so:

public static void MyOrderBy(this List<MySample> list)
{
    list = list.OrderBy(a => a.SortOrder).ThenBy(a => a.Description).ToList();
}

and the use it like so:

samples.MyOrderBy();

It's just an idea though, I don't know if it will work, or if it's a good idea or not.

Problem

I have a question on sorting a list by multiple columns. In the following sample, even though I sorted to show `None, A First Description, B Second...`, the list still prints in the order it was inserted. ``` List<MySample> samples = new List<MySample>(); samples.Add(new MySample { SortOrder = 1, Data = "A First Description", Description = "A First Description" }); samples.Add(new MySample { SortOrder = 1, Data = "C Third Description", Description = "C Third Description" }); samples.Add(new MySample { SortOrder = 1, Data = "B Second Description", Description = "B Second Description" }); samples.Add(new MySample { SortOrder = 0, Data = "None", Description = "None" }); samples.OrderBy(a => a.SortOrder).ThenBy(a => a.Description).ToList(); foreach (var item in samples) { Console.WriteLine(item); } public class MySample { public int SortOrder { get; set; } public string Description { get; set; } public object Data { get; set; } } ``` If I change my code to do the following, then it prints in the desired order. ``` samples = samples.OrderBy(a => a.SortOrder).ThenBy(a => a.Description).ToList(); ``` Can the ordering be done without assigning(like above)? FYI, this example is not actual code. I need to databind this list to a `ComboBox` in `WPF` through code behind using `FrameworkElementFactory`. Thanks for your help! Update with my approach: ``` var collectionView = CollectionViewSource.GetDefaultView(<My list to be sorted>); collectionView.SortDescriptions.Add(new SortDescription("SortOrder", ListSortDirection.Ascending)); collectionView.SortDescriptions.Add(new SortDescription("Description", ListSortDirection.Ascending)); ``` The above did the trick in the UI. I thank all for the fast answers.

Original source