Search code examples
c#linqenumerable

Enumerable OrderBy used to order collection by multiple optional fields


I have to order the child elements of a XML element. The child elements contain multiple elements that are not mandatory.

What I tried so far is:

var orderedElements = parent.Elements("ChildElement")
    .OrderBy(child => child.Element("Field1").Value.ToString())
    .ThenBy(child => child.Element("Field2").Value.ToString())
    .ToList();

The problem is that Field2 is not a mandatory element of ChildElement and I obviously get a null reference exception if Field2 is not present in a ChildElement. Is it possible to modify the argument of ThenBy() to order the ChildElements after Field2 only if Field2 exists in the ChildElements?


Solution

  • Just check if the Field element exists:

    var orderedElements = parent.Elements("ChildElement")
        .OrderBy(child => child.Element("Field1").Value)
        .ThenBy(child => child.Element("Field2") != null ? child.Element("Field2").Value : string.Empty)
        .ToList();
    

    (BTW, you don't need to call ToString() on Value, since it's already a string)