Refactor nested null checking for multiple possible string values I am parsing an XML file and trying to get the guid of a node where it has an attribute "name" and a value of "Name" like so:

&lt;property name="Name" guid="7eca00b3-38e0-f0e8-9b72-2b822b21de6b" /&gt;

string propertyGuid = propertyList.Where(x =&gt; x.name == "Name").FirstOrDefault()?.ToString();
if (propertyGuid == (object)null)     
     throw new ArgumentNullException();


So I just found out that there are nodes that don't have a "Name" value but have a "Code" value. Which lets me check for another null value again

&lt;property name="Code" guid="8bca00b3-38e0-f0e8-9b72-2b822b21de7a" /&gt;

string propertyGuid = propertyList.Where(x =&gt; x.name == "Name").FirstOrDefault()?.ToString();
if (propertyGuid == (object)null)
{
     propertyGuid = propertyList.Where(x =&gt; x.name == "Code").FirstOrDefault()?.ToString();
     if (propertyGuid == (object)null)
          throw new ArgumentNullException();
}


How do I refactor my code such that when another criteria (e.g "ID") is introduced in the future, I don't have to make another nested null check?

EDIT:

The check should be the other way around.

if ((object)propertyGuid == null)
You can just go with :

// Just check both case at the same time
string propertyGuid = propertyList.Where(x =&gt; x.name == "Name" || x.name == "Code").FirstOrDefault()?.ToString();
if (string.IsNullOrEmpty(propertyGuid)) // Same check as you did but written differently
{         
    throw new ArgumentNullException();
}


Then for the future, I guess that you can have Guids on node you don't want to extract. You could have properties on a list or array :

List&lt;string&gt; possibleName = new List&lt;string&gt;() {"Code", "Name"};


And then calling an extract function :

Public static string GetGuid(List&lt;string&gt; possibleName, Whatever propertyList)
{
    string propertyGuid = string.Empty;
    foreach (string name on possibleName)
    {
        propertyGuid = propertyList.Where(x =&gt; x.name == name).FirstOrDefault()?.ToString();
        if (!string.IsNullOrEmpty(propertyGuid))     
        {
             return (propertyGuid);
        }
    }
    throw new ArgumentNullException();
}


Ps : I'd like to add that if propertyList is a NodeList you won't get what you want.