Search code examples
c#.netlinqlistc#-4.0

How to Sort a list by field


Good day 4 u all

I have a list of objects

My objects like

Product = "iPhone"; 
Category = "SmartPhone";

Product = "HP"; 
Category = "PC";

Product = "HTC"; 
Category = "SmartPhone";

And I insert each object into my test so its like

List<Myobject> MyList = new List<Myobject>();

And now I need to sord/order MyList by the category

As I need my list to show the SmartPhone category first then other


Solution

  • You can use List.Sort

    l.Sort((p, q) => p.Category.CompareTo(q.Category));
    

    The advantage over the LINQ OrderBy is that you'll order the list in-place instead of generating an IOrderedEnumerable<T> that then you have to re-transform in a List<T>.