Sinatr Sinatr - 1 month ago 15
C# Question

Optimize LINQ Count() > X

Question: given

IEnumerable<>
, how to check what sequence contains more than
x
items?




MCVE:

static void Main(string[] args)
{
var test = Test().Where(o => o > 2 && o < 6); // ToList()
if (test.Count() > 1) // how to optimize this?
foreach (var t in test) // consumer
Console.WriteLine(t);
}

static IEnumerable<int> Test()
{
for (int i = 0; i < 10; i++)
yield return i;
}


The problem here is what
Count()
will run complete sequence and that's
1E6
+ items (
ToList()
is also bad idea). I am also not allowed to change consumer code (it's a method accepting complete sequence).

Answer

In case of large test collection (when Count() is expensive) you can try a typical trick:

if (test.Skip(1).Any()) 

In general case test.Count() > x can be rewritten into

if (test.Skip(x).Any())