Sort objects in List by properties on the object

后端 未结 2 1770
庸人自扰
庸人自扰 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: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 on your type, and just call

    theList.Sort();
    

    ... which will use the IComparable.CompareTo() implementation.

提交回复
热议问题