如果LINQ的结果为空 [英] If Linq Result Is Empty

查看:126
本文介绍了如果LINQ的结果为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个LINQ查询,看起来像这样,我怎么可以检查,看看是否有没有通过查询发现结果?



  VAR LinqResult = $ b从在Db.Table 
$ b其中a.Value0 ==忍者
组由a.Value1为b
选择新{表= b};

如果(LinqResult.Count()== 0)//?
{

}


解决方案

您应该尽量避免使用计数()方法,以此来检查序列是否为空或没有。菲尔哈克有在其博客上的优秀文章在那里,他讨论了这个反模式。



计数() 必须实际枚举序列的所有元素。 - 如果序列是基于多LINQ操作(或来自数据库),其可能是昂贵的



您应该使用 任何() 扩展方法来代替 - 这只是尝试,看看是否有列表中的至少一个元素,但不会列举整个序列

 如果(!LinqResult.Any())
{
//你的代码
}

我个人也认为使用的 任何() 而不是的 计数() 更好的表达你的意图,并且更易于重构或将来可靠地改变。



顺便说一句,如果你真正想要的是第一个(或唯一的)序列的成员,您应该使用的的 第一() 或的 单() 运营商来代替。


If I have a linq query that looks like this, how can I check to see if there were no results found by the query?

var LinqResult = 
    from a in Db.Table
    where a.Value0 == "ninja"
    group a by a.Value1 into b
    select new { Table = b};

if(LinqResult.Count() == 0) //?
{

}

解决方案

You should try to avoid using the Count() method as a way to check whether a sequence is empty or not. Phil Haack has an excellent article on his blog where he discusses this antipattern.

Count() must actually enumerate all elements of the sequence - which may be expensive if the sequence is based on multiple LINQ operations (or comes from a database).

You should use the Any() extension method instead - which only attempts to see if there is at least one element in the list, but will not enumerate the entire sequence.

if( !LinqResult.Any() )
{ 
   // your code
} 

Personally, I also think that the use of Any() rather than Count() better expresses your intent, and is easier to refactor or change reliably in the future.

By the way, if what you actually want is the the first (or only) member of the sequence you should use either the First() or Single() operators instead.

这篇关于如果LINQ的结果为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆