c# - LINQ Count() until, is this more efficient? -


say want check whether there @ least n elements in collection.

is better doing?

count() >= n

using:

    public static bool atleast<t>(this ienumerable<t> enumerable, int max)     {         int count = 0;         return enumerable.any(item => ++count >= max);     } 

or even

    public static bool equals<t>(this ienumerable<t> enumerable, int amount)     {         return enumerable.take(amount).count() == amount;     } 

how benchmark this?

    /// <summary>     /// returns whether enumerable has @ least provided amount of elements.     /// </summary>     public static bool hasatleast<t>(this ienumerable<t> enumerable, int amount)     {         return enumerable.take(amount).count() == amount;     }      /// <summary>     /// returns whether enumerable has @ provided amount of elements.     /// </summary>     public static bool hasatmost<t>(this ienumerable<t> enumerable, int amount)     {         return enumerable.take(amount + 1).count() <= amount;     } 

there well-documented optimizations built in .count() method. specifically, if enumerable icollection, .count() constant-time operation use icollection's .count property.

however, in general case iterate entire ienumerable count. if not have icollection, you'd better off using either of 2 suggested methods when there more n elements. relative performance of two, you'd have profile them others have suggested.


Comments

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -