score:6

Accepted answer

You can use Enumerable.DefaultIfEmpty and specify a custom default value:

var result = componentData.Where(n => !string.IsNullOrEmpty(n.CompName))
                          .DefaultIfEmpty(componentData.ElementAtOrDefault(0))
                          .First();

Note that you can now use First safely since the sequence cannot be empty anymore. ElementAtOrDefault will return default(T)(null for reference types) if the source sequence is empty. This will prevent an exception when you use the indexer of an IList<T> directly.

score:2

var tt = componentData.FirstOrDefault(n=!string.IsNullOrEmpty(n.CompName)) ?? componentData[0];

Although you would want to check that componentData was not null and count/length was greater than zero first too.

score:11

Take the line you currently have and add ?? componentData[0] at the end.

?? is the null coalescing operator. It's just shorthand for, "if what's to my left is null, return what's on my right. If it's not null, return that."


Related Query