How to check for null before I use in linq?

廉价感情. 提交于 2021-02-07 11:15:32

问题


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?


回答1:


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

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



回答2:


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




回答3:


You can just make your predicate check for null...

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



回答4:


I would do something like this:

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


来源:https://stackoverflow.com/questions/5601397/how-to-check-for-null-before-i-use-in-linq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!