Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short Circuit Linq for (Count > 1) [duplicate]

Tags:

c#

linq

One of the advantages of linq.Any() is that it short Circuits once the first result is returned, so is O(1) not O(n).

If I want to check if Linq.Count() > n where n > 1, what is the optimal way to short circuit the expression, so that it doesn't significantly slow things down when Linq.Count() is close to n, but speeds things up when Linq.Count() is large.

like image 529
Yair Halberstadt Avatar asked Dec 21 '25 09:12

Yair Halberstadt


1 Answers

I used

Linq.Skip(n).Any();

If you know that no elements are null, you could use

Linq.ElementAtOrDefault(n) != null

Although I don't know if there would be any speed advantage to this.

like image 148
Yair Halberstadt Avatar answered Dec 23 '25 22:12

Yair Halberstadt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!