我使用Linq- to -XML来做一个简单的“这个用户是否已注册”的检查(这里没有安全性,只是为一个桌面应用程序创建了一个注册用户的列表)。如何处理如下查询的结果:
var people = from person in currentDoc.Descendants("Users")
where (string)person.Element("User") == searchBox.Text
select person;我知道使用结果的最常见方法是这样的
foreach (var line in people){
//do something here
}但是如果person返回的时候是空的怎么办,如果这个人没有注册会发生什么呢?
我在这个网站和MSDN上看了看,还没有找到一个真正明确的答案。
额外的奖励:对people包含的内容进行很好的解释。
发布于 2010-03-30 02:28:00
我读到过在这些情况下使用Any()比==0()更好。E.g
bool anyPeople = people.Any();
if (anyPeople) {有关在Linq中使用Count()对性能影响的更多讨论,请参见http://rapidapplicationdevelopment.blogspot.com/2009/07/ienumerablecount-is-code-smell.html,尤其是在IEnumerable中,其中整个集合都由Count()方法迭代。
同样,使用Any()也可以更清楚地解释你的意图。
发布于 2010-03-30 02:20:23
尝试使用:
from person in currentDoc.Descendants("Users")
where (string)person.Element("User") == searchBox.Text && !person.IsEmpty
select person;上面的代码将只选择非空的person元素。还有一个HasElements属性可以说明它是否有子元素--根据您的XML结构,这个属性可能更好,因为空格make IsEmpty返回false (空格可以算作文本)。
people变量将是一个IEnumerable<XElement>变量,因为您似乎正在查询一个XElement集合。var关键字只是一个快捷方式,它允许编译器输入变量,因此您不需要事先确定类型并使用List<XElement> people = ...
发布于 2010-03-30 02:18:05
你可以只做一个people.Count(),如果你得到0,你就知道那个人没有注册。
https://stackoverflow.com/questions/2540220
复制相似问题