In C# 6 it would be easy with the new
?.
operator:
FaType = (string)item.Element("AlternateFALIST")?.Element("AlternateFA")?.Element("FaType") ?? ""
Otherwise, I'd suggest using a separate (or anonymous or lambda) method to walk to the
FAType
:
private static XElement SafePathWalker(XElement start, params string[] elementNames)
{
XElement result = start;
foreach (string name in elementNames)
{
result = result.Element(name);
if (result == null)
return null;
}
return result;
}
Then:
FaType = (string)SafePathWalker(item, "AlternateFALIST", "AlternateFA", "FAType") ?? ""
Edit: MTH
The
SafePathWalker
could be put into an extension methods class:
public static ExtensionMethods
{
public static XElement SafePathWalker(this XElement start, params string[] elementNames)
{
XElement result = start;
for (int i = 0; result != null && i < elementNames.Length; ++i)
{
result = result.Element(elementNames[i]);
}
return result;
}
}
Then:
FaType = (string)item.SafePathWalker("AlternateFALIST", "AlternateFA", "FAType") ?? ""