Sort list by field (C#)

后端 未结 8 1243
一向
一向 2021-01-01 09:09

I have class like:

class SortNode
{
    public Int32 m_valRating = 0;

    public SortNode(Int32 valRating)
    {
        this.m_valRating = valRating;
    }         


        
8条回答
  •  北荒
    北荒 (楼主)
    2021-01-01 09:39

    In-place:

    refSortNodeList.Sort(
      (x, y) =>
        x == null ? (y == null ? 0 : -1)
          : (y == null ? 1 : x.m_valRating.CompareTo(y.m_valRating))
    );
    

    Creating a new enumeration:

    var newEnum = refSortNodeList.OrderBy(x => x.m_valRating);
    

    Creating a new list:

    var newList = refSortNodeList.OrderBy(x => x.m_valRating).ToList();
    

    In-place is fastest and most memory efficient, but no good if you want to also retain the old list.

    The next is faster than the last and gives results as they go, but you have to re-do the sort to use it again, in which case the third is the one to go for.

提交回复
热议问题