如何知道我的linq查询是否返回null [英] how to know if my linq query returns null

查看:92
本文介绍了如何知道我的linq查询是否返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个linq查询:

I have this linq query :

var myQuery = from Q in myDataContext
          select Q.Name

,当我尝试这样做时: listView.ItemsSource = myQuery

and when I try to do this : listView.ItemsSource = myQuery

有时会抛出异常,因为myQuery

it sometimes throws an exception because there are no elements in myQuery

我尝试了很多方法,例如:if(myQuery.count!=0)if(myQuery.Any()) 但没有任何效果,那么如何确定查询是否返回空值?

I tried many ways like : if(myQuery.count!=0) or if(myQuery.Any()) but nothing worked , so how can I determine if my Query return null ?

推荐答案

您可以将结果显示为列表:

You can realise the result as a list:

var myQuery = (from Q in myDataContext select Q.Name).ToList();

现在您可以检查项目数:

Now you can check the number of items:

if (myQuery.Count > 0) ...

您还可以在原始查询上使用Count()方法,但是随后您将运行两次查询,一次对项目进行计数,一次来使用它们.

You could also use the Count() method on the original query, but then you would be running the query twice, once to count the items, and once to use them.

这篇关于如何知道我的linq查询是否返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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