How to get the first two events using LINQ?

I need to know the number of elements that satisfy the condition, so I do the following:

int numberOfItems = context.SomeEntity.Count(someCondition); 

but since I only need to check, and only if numberOfItems is exactly 1, I would like to improve this query and be more efficient by stopping the count of elements when the first two occurrences satisfy the condition (when the first 2 occurrences satisfy the condition, there is no need to continue to check it ) Doing something like:

 bool existsOnlyOne = context.SomeEntity.... 

How to do it?

+4
source share
1 answer

You can change the condition to

 bool existsOnlyOne = context.SomeEntity.Where(someCondition).Take(2).Count() == 1; 

If you have more than two elements, elements from the third will be ignored by the Take(2) method.

+4
source

Source: https://habr.com/ru/post/1484029/


All Articles