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.
I've read that it's better to use Any() rather than Count()==0 in these situations. E.g
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()
As told by Matt use
Count()==0
orAny()
.people is
IEnumerable<XElement>
I think.Try using:
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 makeIsEmpty
return false (blank space can count as text).The
people
variable is going to be anIEnumerable<XElement>
variable, as you appear to be querying a collection ofXElement
. 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 useList<XElement> people = ...
You could just do a people.Count() and if you get 0, you know that person is not registered.