Problem comparing items implementing IComparable

前端 未结 2 1307
小鲜肉
小鲜肉 2021-01-13 10:18

I am working on a extension method where it finds the min item by specific selector. Below the code

    public static T MinBy(this IEnumerable<         


        
2条回答
  •  再見小時候
    2021-01-13 10:52

    IComparable doesn't provide operator support - you need to use current.CompareTo(min). Or better, use Comparer.Default.Compare(current,min) - then you can drop the constraint and it'll handle nulls etc automatically, and it'll avoid boxing.

    var comparer = Comparer.Default;
    ...
    // loop
        if(comparer.Compare(current, min) < 0) {...}
    

提交回复
热议问题