在Linq-to-xml中检查结果是否存在 [英] Check for Existence of a Result in Linq-to-xml

查看:79
本文介绍了在Linq-to-xml中检查结果是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Linq-to-XML进行简单的此用户已注册"检查(此处没有安全性,仅列出台式机应用程序的已注册用户).我该如何处理类似这样的查询的结果:

I'm using Linq-to-XML to do a simple "is this user registered" check (no security here, just making a list of registered users for a desktop app). How do I handle the result from a query like this:

var people = from person in currentDoc.Descendants("Users")
                     where (string)person.Element("User") == searchBox.Text
                     select person;

我了解使用结果的最常见方式是

I understand the most common way to use the result would be something like

foreach (var line in people){
    //do something here
}

但是如果person返回空状态,该怎么办?如果此人未注册,会发生什么?

but what do you do if person comes back empty, which is what would happen if the person isn't registered?

我已经在该站点和MSDN上四处张望,还没有找到一个明确的答案.

I've looked around on this site and on MSDN and haven't found a really clear answer yet.

额外的功劳:很好地解释people包含的内容.

Extra credit: Give a good explanation of what people contains.

推荐答案

我读到在这种情况下,最好使用Any()而不是Count()== 0.例如

I've read that it's better to use Any() rather than Count()==0 in these situations. E.g

bool anyPeople = people.Any();
if (anyPeople) {

请参见 http://rapidapplicationdevelopment.blogspot.com/2009/07/ienumerablecount-is-code-smell.html 进一步讨论了将Count()与Linq(尤其是IEnumerable)一起使用对性能的影响,该方法通过Count()方法对整个集合进行迭代.

See http://rapidapplicationdevelopment.blogspot.com/2009/07/ienumerablecount-is-code-smell.html for more discussion on the performance impact of using Count() with Linq, especially with IEnumerable, where the entire collection is iterated by the Count() method.

也可以使用Any()来更清楚地说明Count()的意图

Also using Any() arguably is a clearer explanation of your intent that Count()

这篇关于在Linq-to-xml中检查结果是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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