Reputation: 85855
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?
Upvotes: 25
Views: 89291
Reputation: 38850
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"
.
Upvotes: 11
Reputation: 6464
I would do something like this:
myClass.Where(x => x.MyOtherObject != null)
.Where(y => y.MyOtherObject.Name = "Name")
.ToList();
Upvotes: 0
Reputation: 59002
Simple, just add an AND
clause to check if it's not null:
myClass.Where(x => x.MyOtherObject != null && x.MyOtherObject.Name = "Name").ToList();
Upvotes: 49
Reputation: 16718
You can just make your predicate check for null...
myClass.Where(x => (x.MyOtherObject == null) ? false : x.MyOtherObject.Name == "Name").ToList();
Upvotes: 3