c# - Problem comparing items implementing IComparable -


i working on extension method finds min item specific selector. below code

    public static t minby<t, k>(this ienumerable<t> src, func<t, k> selector) k : struct, icomparable, iconvertible     {         var min = default(k);         t minitem = default(t);         foreach (var item in src)         {             var current = selector(item);             if (current < min)             {                 min = current;                 minitem = item;             }         }          return minitem;      } 

it gives error error operator '<' cannot applied operands of type 'k' , 'k'. have specified generic constraint k should struct , icomparable. believe numeric data type can satisfied this.

then how come invalid operation.?

icomparable doesn't (and can't) operators. should using:

if (current.compareto(min) < 0) 

operators static, , ever overloaded rather overridden. can't require operators within interfaces, , presence of method doesn't magically change operator do. (for example, overriding equals not change how == behaves.)

you should note constraint talks nongeneric icomparable interface, you're going boxing @ every operation. suggest change constraint icomparable<k> instead. (or drop constraint , use comparer<k>.default marc suggested.)

some other comments method:

  • if of key values more default value k (e.g. k=int , keys positive) won't find item
  • you may wish have overload accepts particular icomparare<k> (but if drop comparable constraint)
  • there's no real need constrain k value type. if wanted find person lexicographically earliest name?
  • if there no elements, return default value t; fit in rest of linq suggest throwing invalidoperationexception
  • i suggest using tsource , tkey type parameters more consistent linq

you may want @ morelinq minby implementation alternative. (looking on again, i'm not sure it's idea require comparer non-null; should use default comparer in same way normal linq if comparer null.)


Comments

Popular posts from this blog

Javascript line number mapping -

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -