I have a List of objects, lets say DataTables.
Is it possible to use an object from the list only if it exists?
For example, if the TableList contains 5 DataTables named a,b,c,d,e.
if (TableList.Any(t => t.TableName == "a"))
{
TableList.First(t => t.TableName == "a").DoStuff();
//OR
DataTable TheReturnOf_a = TableList.First(t => t.TableName == "a");
}
else if (TableList.Any(t => t.TableName == "f"))
{
TableList.First(t => t.TableName == "f")).DoMoreStuff();
}
Assuming TableList
has an element type that is a reference type, you can use FirstOrDefault()
to return the first match or null, then the null conditional operator to only call the method if the target is non-null:
TableList.FirstOrDefault(t => t.TableName == "a")?.DoStuff();
So your original code is equivalent to:
var tableA = TableList.FirstOrDefault(t => t.TableName == "a");
if (tableA != null)
{
tableA.DoStuff();
}
else
{
TableList.FirstOrDefault(t => t.TableName == "f").DoStuff();
}
Alternatively, if you're going to do the same thing to the table you end up using, and you're just trying to get the right table, you could use or null coalescing operator:
// Find an "a" table if possible, but revert to an "f" table otherwise.
var table = TableList.FirstOrDefault(t => t.TableName == "a") ??
TableList.FirstOrDefault(t => t.TableName == "f");
// Call DoStuff() on the table - handling the case where there isn't an
// "a" or an "f" table.
table?.DoStuff();
See more on this question at Stackoverflow