Sean
Sean

Reputation: 23

LINQ - How to select one element based on another element that exists in only some records

I have some code as follows:

XmlDocument xmlGroupInfo = new XmlDocument();
xmlGroupInfo.InnerXml = "<Groups><Group><Name>Test1</Name><Query>Hello</Query></Group><Group><Name>Test0</Name><Query>1 = 0</Query></Group></Groups>";
XElement filterDoc = XElement.Parse(xmlGroupInfo.InnerXml);
var groupsWithFilters2 = filterDoc
    .Descendants("Group")
    .Where(d => d.Element("Query").Value != null)
    .Select(n => new { a = n.Element("Name").Value, b = n.Element("Query").Value });

If I run this query everything works fine - I get a result with both group names and queries since the query element exists in both instances. However, the real case for my data is that this Query element is only present some of the time.

If I remove the Query element from the first part of the XML, I wind up with a null exception. XML would now look like this:

xmlGroupInfo.InnerXml = "<Groups><Group><Name>Test1</Name></Group><Group><Name>Test0</Name><Query>1 = 0</Query></Group></Groups>";

So, how do I accomplish my goal, which is to select the Name element, but only when there is a Query element present that has some non-null value?

Upvotes: 1

Views: 253

Answers (1)

DavidG
DavidG

Reputation: 118987

You just need to cope with the Query element being optional in your Where clause. The easiest way to do that would be like this, by using the null conditional operator:

.Where(d => d.Element("Query")?.Value != null)
//                            ^ this

Upvotes: 1

Related Questions