简体   繁体   中英

Can I use the “Count” property on 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 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?

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

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.

您可以在查询上调用.ToList()以使其执行,然后您可以检查.Count属性的值。

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.

string[] name = new string[] { "Venu", "Bharath", "Sanjay", "Sarath", "Sandhiya", "Banu", "Gowtham", "Abdul Rahman", "Anamika", "Alex", "Austin", "Gilbert" };
var _lqResult = from nm in name where nm.StartsWith("A") select nm;

        if (_lqResult.Count() > 1)
        {
            foreach (var n in _lqResult)
            {
                Console.WriteLine(n);
            }
        }
        else {
            Console.WriteLine("NO RESULT AVAILABLE");
        }

just result.count() will work for LINQ result and i'm using that in many places

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM