Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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.

like image 371
lobsterhat Avatar asked Dec 16 '13 18:12

lobsterhat


2 Answers

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;
like image 198
p.s.w.g Avatar answered Oct 12 '22 13:10

p.s.w.g


I would do this as two statements:

var personContainer = MyObjectList.FirstOrDefault(x => x.Person != null);
string userName = personContainer == null ? string.Empty : personContainer.Person.Name;
like image 32
Reed Copsey Avatar answered Oct 12 '22 13:10

Reed Copsey