Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use the "Count" property on a Linq result?

Tags:

c#

linq

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?

like image 310
Jargalsai Avatar asked Aug 18 '10 04:08

Jargalsai


People also ask

How to Use Count in LINQ?

Syntax: int Count<TSource>(); Count<TSource>(Func<TSource, bool> predicate): This method is used to return the number of items which satisfy the given condition. The return type of this method is System.

How to get Count using LINQ in c#?

Count() methodIEnumerable<string> strings = new List<string> { "first", "then", "and then", "finally" }; // Will return 4 int result = strings. Count(); NOTE: The Count() LINQ method (an extension method to IEnumerable<T> ) is slightly different from the Count property on List<T> .

How to Use Count property in c#?

This method(comes under System. Collections namespace) is used to get the number of elements contained in the Stack. The capacity is the number of elements that the Stack can store and the count is the number of elements that are actually in the Stack.

Can Linq select return null?

It will return an empty enumerable. It won't be null.


1 Answers

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().

like image 65
Yuriy Faktorovich Avatar answered Oct 04 '22 21:10

Yuriy Faktorovich