The following example illustrates how to set a default value for a LINQ to XML query when data is missing:
IEnumerable<Person> persons =
from e in x.Descendants("Person")
select new Person {
Name = e.Value,
Age = (int?)e.Attribute("Age") ?? 21
};
But how do you handle when an attribute is missing altogether? For example what if the node has no parent node?
IEnumerable<Person> persons =
from e in x.Descendants("Person")
select new Person {
Name = e.Value,
Age = (int?)e.Attribute("Age") ?? 21
ParentAge = e.Parent.Attribute("Age")
};
You handle it the hard way, usually with the ternary conditional operator:
To my knowledge, there is no shorter way to do that in C#.