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

问题描述 投票:4回答:5

我的代码如下:

var result = from x in Values where x.Value > 5 select x;

然后,我想检查一下:

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

但是,我得到的错误如下:

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

我可以不用结果写一个foreach吗?

c# linq
5个回答
17
投票

使用result.Count()

更好的存储它

int count = result.Count();

所以你不是多次迭代你的收藏。另一个问题是

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

查看IEnumerable.Any()扩展,如果你想要if if执行,如果有任何项目。使用该扩展意味着您不会像使用IEnumerable.Count()那样迭代集合。


7
投票

LINQ使用扩展方法,因此您需要包括括号:result.Count()

但LINQ有一个Any()方法。因此,如果你需要做的就是找出是否有超过0项,你可以使用任何......

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

...然后LINQ不必遍历整个集合来获取计数。


2
投票

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


0
投票

正如已经说过的那样,你需要一个Count()扩展方法。但是,它需要迭代集合的所有元素来计算它们(通常情况下)。如果元素的数量可能很大而您只需要检查此数字是否等于1,则可以使用Take()方法:


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

它看起来不太好但会阻止对整个结果的迭代。


0
投票
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");
        }

只是result.count()将适用于LINQ结果,我在很多地方使用它

© www.soinside.com 2019 - 2024. All rights reserved.