如何使用Linq使用FirstOrDefault处理NULL对象属性 [英] How to handle NULL object property with FirstOrDefault using Linq
问题描述
我的实际应用程序问题看上去完全像下面的
my real application issue looks exactly like below
Employee empl = new Employee(397947, "David", "Redson", 80000);
employees.Add(empl);
employees.Add(new Employee(174966, "Alfred", "Swanson", 50000));
employees.Add(new Employee(848024, "Alima", "Bieyrou", 40000));
employees.Add(new Employee(number: 397462, fName: "Robert",
lName: "Nants", salary: 30000));
string s = employees.Where(a => a.EmployeeNumber == 20000).FirstOrDefault().FirstName;
当我使用FirstOrDefault时,如果没有匹配的记录,它将引发错误.如果有匹配的记录,我想返回该值,否则它可以为null或为空.
As I am using FirstOrDefault, it is throwing error when there is no matching record. If there is a matching record, I want to return the value, or else it can be null or empty..
推荐答案
在这种情况下,您无需使用Where
和FirstOrDefault
,您可以在FirstOrDefault
自身内部指定过滤条件.但是如果没有满足条件的记录将为您提供null(因为在没有第一个值的情况下它将为您提供默认值,对于引用类型对象,默认值为null
),则应检查NullReferenceException
.所以像这样使用:
You need not to use Where
and the FirstOrDefault
in this case, you can specify the filter condition inside the FirstOrDefault
itself. But which will give you null if there are no records satisfying the condition(because in the absence of first value it will give you the default value, for reference type objects the default value is null
), you you should check for null
before accessing the value, which will throws NullReferenceException
. So Use like this:
var Employee=employees.FirstOrDefault(a => a.EmployeeNumber == 20000);
if(Employee!=null)
{
string employee_name=Employee.FirstName;
// code here
}
否则,您可以使用?.
这样检查null
:
Or else you can use ?.
to check for null
like this:
string employee_name = employees.FirstOrDefault(a => a.EmployeeNumber == 20000)?.FirstName;
这篇关于如何使用Linq使用FirstOrDefault处理NULL对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!