简体   繁体   English

使用具有一些空值的linq遍历数组

[英]Iterate through an array with linq which have some null values

I have an Array of Questions , some of them are null and some of them have something. 我有一个问题数组,其中有些是空的,有些是有问题的。 like this : 像这样 :

Questions = {null , null , object , null , object}

Is the any way to use linq on this array ? 有什么办法可以在这个数组上使用linq吗?

Questions.Where(x => x.someValue == OtherValue).ToList();

This gives me error 这给我错误

Thanks. 谢谢。

You are getting the error because you try to check for a property on a null object. 您收到错误消息是因为您尝试检查null对象上的属性。 Try this: 尝试这个:

Questions.Where(x => (x != null) && (x.someValue == OtherValue)).ToList();

Like this, the compiler won't look into the 2nd condition ( x.someValue == OtherValue ) if the first condition is false. 这样,如果第一个条件为false,则编译器将不会查看第二个条件( x.someValue == OtherValue )。

You could filter out the null values first: 您可以先过滤掉空值:

Questions
    .Where(x => x != null)
    .Where(x => x.someValue == OtherValue)
    .ToList();

您可以使用C#6功能Null条件运算符

Questions.Where(x => x?.someValue == OtherValue).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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