List.Sort in C#: comparer being called with null object

后端 未结 7 1234
攒了一身酷
攒了一身酷 2021-01-01 11:48

I am getting strange behaviour using the built-in C# List.Sort function with a custom comparer.

For some reason it sometimes calls the comparer class\'s Compare meth

7条回答
  •  忘掉有多难
    2021-01-01 12:39

    Marc's answer is useful. I agree with him that the NullReference is due to calling CompareTo on a null property. Without needing an extension class, you can do:

    mylist.Sort((x, y) => 
          (Comparer.Default.Compare(x.SomeProp, y.SomeProp)));
    

    where SomePropType is the type of SomeProp

提交回复
热议问题