开发者

How to check for null before I use in linq?

开发者 https://www.devze.com 2023-02-22 22:53 出处:网络
I have an list of objects that contains another object in it. List<MyClass> myClass = new List<MyClass>();

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.开发者_如何学JAVAWhere(x => x.MyOtherObject.Name = "Name").ToList();

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


Simple, just add an AND clause to check if it's not null:

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


You can just make your predicate check for 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();
0

精彩评论

暂无评论...
验证码 换一张
取 消