c# - How to create empty-conditional operator for collections similar to null-conditional operator? -


c# 6.0 introduced null-conditional operator, big win.

now have operator behaves it, empty collections.

region smallestfittingfreeregion = freeregions             .where(region => region.rect.w >= width && region.rect.h >= height)                             .minby(region => (region.rect.w - width) * (region.rect.h - height)); 

now blows if where returns empty ienumerable, because minby (from morelinq) throws exception if collection empty.

before c# 6.0 solved adding extension method minbyordefault.

i re-write this: .where(...)?.minby(...). doesn't work because .where returns empty collection instead of null.

now solved introducing .nullifempty() extension method ienumerable. arriving @ .where(...).nullifempty()?.minby().

ultimately seems awkward because returning empty collection has been preferable returning null.

is there other more-elegant way this?

imho, "most elegent" solution re-write minby make in minbyordefault

public static tsource minbyordefault<tsource, tkey>(this ienumerable<tsource> source,     func<tsource, tkey> selector) {     return source.minbyordefault(selector, comparer<tkey>.default); }  public static tsource minbyordefault<tsource, tkey>(this ienumerable<tsource> source,     func<tsource, tkey> selector, icomparer<tkey> comparer) {     if (source == null) throw new argumentnullexception("source");     if (selector == null) throw new argumentnullexception("selector");     if (comparer == null) throw new argumentnullexception("comparer");     using (var sourceiterator = source.getenumerator())     {         if (!sourceiterator.movenext())         {             return default(tsource); //this line changed.         }         var min = sourceiterator.current;         var minkey = selector(min);         while (sourceiterator.movenext())         {             var candidate = sourceiterator.current;             var candidateprojected = selector(candidate);             if (comparer.compare(candidateprojected, minkey) < 0)             {                 min = candidate;                 minkey = candidateprojected;             }         }         return min;     } } 

i don't see need special operator.


Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

Cross-Compiling Linux Kernel for Raspberry Pi - ${CCPREFIX}gcc -v does not work -

java.lang.NoClassDefFoundError When Creating New Android Project -