Check for Existence of a Result in Linq-to-xml

2019-07-13 17:43发布

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
}

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

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

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

4条回答
冷血范
2楼-- · 2019-07-13 18:13

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) {

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.

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

查看更多
\"骚年 ilove
3楼-- · 2019-07-13 18:23

As told by Matt use Count()==0 or Any().

people is IEnumerable<XElement> I think.

查看更多
地球回转人心会变
4楼-- · 2019-07-13 18:25

Try using:

from person in currentDoc.Descendants("Users")
where (string)person.Element("User") == searchBox.Text && !person.IsEmpty
select person;

The above will select only non-empty person elements. There is also a HasElements property that says whether or not it has any child elements - this may be better to use depending on your XML structure, as blank space make make IsEmpty return false (blank space can count as text).

The people variable is going to be an IEnumerable<XElement> variable, as you appear to be querying a collection of XElement. The var keyword is simply a shortcut to allow it the variable to be typed by the compiler, so you didn't need to figure out the type beforehand and use List<XElement> people = ...

查看更多
相关推荐>>
5楼-- · 2019-07-13 18:26

You could just do a people.Count() and if you get 0, you know that person is not registered.

查看更多
登录 后发表回答