简体   繁体   English

我可以在Linq结果上使用“Count”属性吗?

[英]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? 我可以不用结果写一个foreach吗?

Use result.Count() . 使用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. 检查IEnumerable.Any()扩展名,如果你想要if if执行,如果有任何项目。 Using that extension means you won't be iterating over the collection as you would with IEnumerable.Count() . 使用该扩展意味着您不会像使用IEnumerable.Count()那样迭代集合。

LINQ uses extension methods , so you need to include the parentheses: result.Count() LINQ使用扩展方法 ,因此您需要包括括号: result.Count()

But LINQ has an Any() method. 但是LINQ有一个Any()方法。 So if all you need to do is find out whether there were more than 0 items, you can use Any... 因此,如果你需要做的就是找出是否有超过0项,你可以使用Any ...

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

...and then LINQ doesn't have to loop through the whole set to get the count. ...然后LINQ不必遍历整个集合来获取计数。

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

As it was already said you'll need a Count() extension method. 正如已经说过的那样,你需要一个Count()扩展方法。 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: 如果元素的数量可能很大而您只需要检查此数字是否等于1,则可以使用Take()方法:


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 只是result.count()将适用于LINQ结果,我在很多地方使用它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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