如何判断linq的结果集为空?

vinsonwolf 2009-12-09 04:39:12
有一段代码,从配置文件里查找对应的Element,

string url = Server.MapPath("process.xml");
XElement processes = XElement.Load(url);
var bench = from elm in processes.Elements()
where elm.Attribute(XName.Get("GUID")).Value == id
select elm;


由于查找的结果为空,所以当我使用bench.Count()时,VS提示说 threw an exception of type "System.NullReferenceException"

不明白为何bench.Count()不能直接返回0呢?
...全文
301 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
vinsonwolf 2009-12-10
  • 打赏
  • 举报
回复
是我错了,在配置文件中Guid是作为element,而不是Attribute,代码错了。
wuyq11 2009-12-09
  • 打赏
  • 举报
回复
使用可空类型Nullable
select (int?)elm
xiaoyuzi 2009-12-09
  • 打赏
  • 举报
回复
public static int Count<TSource>(this System.Collections.Generic.IEnumerable<TSource> source)
Member of System.Linq.Enumerable

bench.Count<类型>()
vinsonwolf 2009-12-09
  • 打赏
  • 举报
回复
linq狠就狠在于此,bench的结果集为空,但是bench不为空啊
NewUser2008 2009-12-09
  • 打赏
  • 举报
回复
if object is null

111,120

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧