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<
IComparable
doesn't (and can't) say anything about operators. You should be using:
if (current.CompareTo(min) < 0)
Operators are static, and only ever overloaded rather than overridden. You can't require operators within interfaces, and the presence of a method doesn't magically change what an operator will do. (For example, overriding Equals
does not change how ==
behaves.)
You should also note that as your constraint only talks about the nongeneric IComparable
interface, you're going to be boxing at every operation. I would suggest you change the constraint to IComparable
instead. (Or drop the constraint and just use Comparer
as Marc suggested.)
Some other comments about your method:
K
(e.g. K=int and all the keys are positive) then you won't find an itemIComparare
(but only if you drop the comparable constraint)K
to a value type. What if I wanted to find the person with the lexicographically earliest name?T
; to fit in with the rest of LINQ I would suggest throwing InvalidOperationException
TSource
and TKey
as the type parameters to be more consistent with LINQYou may want to look at the MoreLINQ MinBy implementation as an alternative. (Looking over that again, I'm not sure it's a good idea for us to require that comparer
is non-null; it should probably use the default comparer in the same way as normal LINQ does if the comparer is null.)