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?
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.
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> .
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.
It will return an empty enumerable. It won't be null.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With