Sort objects in List by properties on the object

后端 未结 2 1767
庸人自扰
庸人自扰 2021-02-07 21:40

I have a List of objects in C#. All the objects contain properties code1 and code2 (among other properties). The list of objects is in no particular order. I need to sort the li

相关标签:
2条回答
  • 2021-02-07 21:45

    You could use linq extensions (leaving the original list unsorted):

    var sorted = theList.OrderBy(o => o.code1).ThenBy(o => o.code2);
    

    To replace the original list with a sorted one, make a slight amendment (not very efficient, it creates a new list):

    theList = theList.OrderBy(o => o.code1).ThenBy(o => o.code2).ToList();
    

    This assumes that your list is of the correct type, something like:

    List<MyClass> theList = new List<MyClass>();
    

    And not a list of objects, in which case you would need to make use of .Cast<>() or .OfType<>().

    0 讨论(0)
  • 2021-02-07 21:56

    Note that Adam Houldsworth's answer with the .ToList() call needlessly creates a new list. If your list is large, this may create unacceptable memory pressure. It would most likely be better to sort the list in place by providing a custom comparison function:

    theList.Sort((a, b) =>
        {
            var firstCompare = a.code1.CompareTo(b.code1);
            return firstCompare != 0 ? firstCompare : a.code2.CompareTo(b.code2);
        });
    

    Alternatively, if this ordering is an intrinsic property of your type, you could implement IComparable<T> on your type, and just call

    theList.Sort();
    

    ... which will use the IComparable<T>.CompareTo() implementation.

    0 讨论(0)
提交回复
热议问题