[英]How does FirstOrDefault evaluate an inner FirstOrDefault with a condition?
I have this issue where FirstOrDefault always returns the first item it encounters regardless of how the inner expression evaluated.我有这个问题,无论内部表达式如何评估,FirstOrDefault 总是返回它遇到的第一个项目。
Lets say I have an array of companies.可以说我有很多公司。
Companies = {Company1, Company2, Company3}
.. and Each company contains an array of employee names. ..每个公司都包含一组员工姓名。
Company1.EmployeeList = {"Employee1", "Employee2"}
Company2.EmployeeList = {"Employee3", "Employee4"}
Company3.EmployeeList = {"Employee5", "Employee6"}
Why do I always receive the first company with the following code?为什么我总是收到带有以下代码的第一家公司?
var myCompany = Companies.FirstOrDefault(c=> c.EmployeeList.FirstOrDefault(name => name == "Employee3") != null);
I run this code:我运行这段代码:
string[] s1 = new [] {"Employee1", "Employee2"};
string[] s2 = new [] {"Employee3", "Employee4"};
string[] s3 = new [] {"Employee5", "Employee6"};
string[][] s = new [] { s1,s2,s3 };
var result = s.FirstOrDefault(c => c.FirstOrDefault(n => n == "Employee3") != null);
And the result is:结果是:
String [] (2 items)
Employee3
Employee4
Is your example not telling the whole story?你的例子没有说明整个故事吗?
Company1
have Employee3
somewhere in their EmployeeList
? Company1
在其EmployeeList
Employee3
Employees
not actually String
(ie is the ==
overloaded or similar) Employees
实际上不是String
(即==
是否重载或类似) As a start, I'd recommend changing your code to use Any
rather than FirstOrDefault != null
首先,我建议您将代码更改为使用
Any
而不是FirstOrDefault != null
var myCompany = Companies
.FirstOrDefault(c => c.EmployeeList.Any(name => name == "Employee3"));
I also notice that you state:我还注意到你 state:
FirstOrDefault always returns the first item it encounters regardless of how the inner expression evaluated
无论内部表达式如何评估,FirstOrDefault 总是返回它遇到的第一个项目
If this is the case, either you have overloaded FirstOrDefault
in some way (unlikely) or your inner expression is always true for every example you've tried (ie in the example, the EmployeeList
of your first Company
has an element that == "Employee3"
is true for).如果是这种情况,要么您以某种方式重载
FirstOrDefault
(不太可能),要么您的内部表达式对于您尝试过的每个示例总是正确的(即在示例中,您的第一个Company
的EmployeeList
有一个元素== "Employee3"
是真的)。
Edit编辑
Two great recommendations from comments:来自评论的两个很好的建议:
ingo suggets using list.Contains(item)
rather than list.Any(el => el == item)
which means using: ingo 建议使用
list.Contains(item)
而不是list.Any(el => el == item)
这意味着使用:
var myCo = Companies.FirstOrDefault(c => c.EmployeeList.Contains("Employee3"));
John L suggests that the items ( Employee
?) in EmployeeList
are value types or similar, such that default(Employee)
is not null
. John L 建议
EmployeeList
中的项目( Employee
?)是值类型或类似的,因此default(Employee)
不是null
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.