tags:

views:

121

answers:

5

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 like:

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

Can I do this without writing a foreach over result?

+9  A: 

Use result.Count().

Better yet store it

int count = result.Count();

So you aren't iterating over your collection multiple times. Another problem is

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

Check out the IEnumerable.Any() extension, if you meant for the if to execute if there are any items. Using that extension means you won't be iterating over the collection as you would with IEnumerable.Count().

Yuriy Faktorovich
D'oh, how simple. Thanks.
Jargalsai
+4  A: 

LINQ uses extension methods, so you need to include the parentheses: result.Count()

But LINQ has an Any() method. So if all you need to do is find out whether there were more than 0 items, you can use Any...

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

...and then LINQ doesn't have to loop through the whole set to get the count.

Kyralessa
A: 

You could call .ToList() on the query to have it executed and then you could check the value of the .Count property.

thekaido
A: 

As it was already said you'll need a Count() extension method. However, it will need to iterate over all elements of the collection to count them (in general case). If the number of elements could be large and you only need to check that this number is equal to 1 you can use Take() method:


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

It looks not so nice but will prevent iteration over entire result.

Konstantin Oznobihin
A: 

result.Count is a method, 0 is an integer, hence the error message ' cannot be applied to operands of type 'method group' and 'int' '. You don't want to compare result.Count to 0, but the result of the method, so use 'result.Count()' instead of 'result.Count'.

dkson