lobsterhat lobsterhat - 3 months ago 21
C# Question

LINQ - Returning value of a property of an object that is not null

I have a list of objects that contain a Person object which may have a null. What I'd like to do is get the value of the Name property of the first Person object that is not null and if all Person objects are null, return an empty string.

My best attempt is as follows:

string userName = MyObjectList.FirstOrDefault(x => x.Person != null).Person.Name ?? string.Empty;


I think I understand why this doesn't work; if Person is null for each object in my list, then we get the default value, which would be null and will throw a null reference error when I try to access the property Person.

I can get the result I want by checking if any object is not null and then getting the first, but I'd rather accomplish this in one LINQ statement. Any input is appreciated, thanks.

Answer

The usual trick would look something like this:

string userName = MyObjectList.Where(x => x.Person != null)
                              .Select(x => x.Person.Name)
                              .FirstOrDefault() ?? string.Empty;

Or following Servy's suggestion:

string userName = MyObjectList.Where(x => x.Person != null)
                              .Select(x => x.Person.Name)
                              .DefaultIfEmpty(string.Empty)
                              .First();

Update it's now relatively easy to do this with C# 6's null-conditional operators:

string userName = MyObjectList.FirstOrDefault(x => x.Person != null)?.Person.Name ?? string.Empty;