使用具有一些空值的linq迭代数组

Ami*_*udi 0 c# linq arrays

我有一个问题数组,其中一些是空的,其中一些有一些东西.像这样 :

Questions = {null , null , object , null , object}
Run Code Online (Sandbox Code Playgroud)

有没有办法在这个阵列上使用linq?

Questions.Where(x => x.someValue == OtherValue).ToList();
Run Code Online (Sandbox Code Playgroud)

这给了我错误

谢谢.

iul*_*net 6

您收到错误是因为您尝试检查null对象上的属性.试试这个:

Questions.Where(x => (x != null) && (x.someValue == OtherValue)).ToList();
Run Code Online (Sandbox Code Playgroud)

像这样,x.someValue == OtherValue如果第一个条件为false ,编译器将不会查看第二个条件().