简体   繁体   中英

How to check for null before I use in linq?

I have an list of objects that contains another object in it.

List<MyClass> myClass = new List<MyClass>();

I want to do some linq like this

myClass.Where(x => x.MyOtherObject.Name = "Name").ToList();

Thing is sometimes "MyOtherObject" is null. How do I check for this?

简单,只需添加一个AND子句来检查它是否为空:

myClass.Where(x => x.MyOtherObject != null && x.MyOtherObject.Name = "Name").ToList();

As of C# 6, you can also use a null conditional operator ?. :

myClass.Where(x => x.MyOtherObject?.Name == "Name").ToList();

This will essentially resolve the Name property to null if MyOtherObject is null, which will fail the comparison with "Name" .

Try it online

你可以让你的谓词检查为null ...

myClass.Where(x => (x.MyOtherObject == null) ? false : x.MyOtherObject.Name == "Name").ToList();

I would do something like this:

myClass.Where(x => x.MyOtherObject != null)
       .Where(y => y.MyOtherObject.Name = "Name")
       .ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM