views:

151

answers:

1

So, I've got a small chunk of stabby, pointy xml that looks like this:

<Groups UseGroup='True'>
     <Group>1264,182,1979</Group>
</Groups>

And I've got a small chunk of linq that gets the value from that looks like this:

var group = from a in xml.Descendants("Groups")
      select a.Element("Group").Value;

It's all fine and dandy but I don't know how to handle a null response? If I use:

if(group != null)

It will always evaluate true because there is something there. If I use:

if(group.ToString() == "")

It will always evaluate true because ToString() called on that object returns System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Xml.Linq.XElement,System.String] For some reason, I'm having a hard time casting my result from my linq query to a string so I'm using var because that seems to be the only way I can get it to work...

So the question is, am I using the correct linq syntax and if so, how do i tell if it returned anything or not?

+2  A: 

I'm not sure why Eric posted his answer as a comment, but he's correct. Your conditional statement should read:

if (group.Any())

If your XML has no "Groups" tags, then Any() will evaluate to false.

You can think of group as being a sequence of all the matches to your query. In your example, there's only one match, but that just means it's an IEnumerable with only one value. To get that value, you can do:

string groupVal = group.FirstOrDefault();

That will return the first match, or a null string if there are no matches. You can use Single() if you want there to be exactly one result, and you want to throw an exception if there are zero or many results. There are also First() and SingleOrDefault() methods that behave as you might expect.

Joel Mueller
ah, that makes a lot of sense - thanks so much!
onekidney