Can I use the Count property for a Linq result?

I have code like:

var result = from x in Values where x.Value > 5 select x;

Then I want to check:

if(result.Count > 0) { ... }
else if(result.Count == 1) { ... }
else { throw new Exception(...); }

However, I get errors such as:

error CS0019: Operator '==' cannot be applied to operands of type 'method group' and 'int'

Can I do this without recording the foreach result?

+3
source share
4 answers

Use result.Count().

Better yet save it

int count = result.Count();

So, you do not repeat your collection several times. Another problem:

if(result.Count() > 0) { ... }
else if(result.Count() == 1) { ... } //would never execute
else { throw new Exception(...); }

Check the extension IEnumerable.Any()if you were intended to do if if there are any elements. Using this extension means that you will not iterate over the collection, as it would with IEnumerable.Count().

+17
source

LINQ uses extension methods , : result.Count()

LINQ Any(). , , 0 , Any...

if (result.Any())
    // then do whatever

... LINQ , .

+7

You can call .ToList () in the request so that it is executed, and then you can check the value of the .Count property.

+2
source

As already mentioned, you will need the Count () extension method. However, for their calculation, it will be necessary to sort through all the elements of the collection (in the general case). If the number of elements can be large, and you only need to check that this number is 1, you can use the Take () method:


else if (result.Take(2).Count() == 1)

This does not look so good, but will prevent iteration over the entire result.

0
source

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


All Articles