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.


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;

我会这样做两个陈述:

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

You are accessing a null object and trying to read its properties.

Look into something like this:

var obj = MyObjectList.FirstOrDefault(x => x.Person != null);
string userName = string.Empty;
if (null != obj) {
    userName = obj.Person.Name;
}

Good luck!

链接地址: http://www.djcxy.com/p/51356.html

上一篇: 根据列表的值清理List with Linq中的某些属性值

下一篇: 返回非空对象的属性值