Lambda表达式,如何在对象内部进行搜索?
我开始喜欢 Lambda 表达式,但我正在努力越过这堵墙:
public class CompanyWithEmployees {
public CompanyWithEmployees() { }
public Company CompanyInfo { get; set; }
public List<Person> Employees { get; set; }
}
我的搜索:
List<CompanyWithEmployees> companiesWithEmployees = ws.GetCompaniesWithEmployees();
CompanyWithEmployees ces = companiesWithEmployees
.Find(x => x.Employees
.Find(y => y.PersonID == person.PersonID));
所以,我想获取对象“CompanyWithEmployees”,其中包含我正在寻找的人员(员工),但我得到“无法将 'Person' 隐式转换为 'bool')”,这是正确的,但如果我不传递 Person 对象,第一个 Find 如何执行?
I'm starting to love Lambda expressions but I'm struggling to pass this wall:
public class CompanyWithEmployees {
public CompanyWithEmployees() { }
public Company CompanyInfo { get; set; }
public List<Person> Employees { get; set; }
}
My search:
List<CompanyWithEmployees> companiesWithEmployees = ws.GetCompaniesWithEmployees();
CompanyWithEmployees ces = companiesWithEmployees
.Find(x => x.Employees
.Find(y => y.PersonID == person.PersonID));
So, I want to get the Object "CompanyWithEmployees" that have that Person (Employee) that I'm looking for, but I'm getting "Cannot implicit convert 'Person' To 'bool')" which is correct, but if I'm not passing the Person object, how can the first Find executes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
因为您想检查是否存在,也许可以尝试:
这将检查具有相同
ParID
的任何Person
; 如果您指的是同一个Person
实例(参考),那么Contains
就足够了:Because you want to check for existance, perhaps try:
This will check for any
Person
with the sameParID
; if you mean the samePerson
instance (reference), thenContains
should suffice:Find()
返回找到的对象。 使用Any()
仅检查表达式对于任何元素是否为 true。Find()
returns the found object. UseAny()
to just check whether the expression is true for any element..Find
返回仅一个对象,x.Employees.Find(..)
返回Person< /代码>。
.Find
需要布尔参数(即条件的结果),这就是为什么会出现编译器错误,提示Cannotimplicit conversion 'Person' To 'bool'
.Where
可以返回多个对象,因此可以迭代所有列表。根据您的情况使用
.Where
和.Any
的组合。下面的代码将说明
.Where
、.Find
和.Any
之间的区别:.Find
returns only one object,x.Employees.Find(..)
returnsPerson
..Find
expects boolean parameter(i.e. the result of conditions), that's why there's a compiler error that saysCannot implicit convert 'Person' To 'bool'
.Where
can return multiple objects, hence can iterate through all list.use a combination of
.Where
and.Any
in your case.the following code will illustrate the difference between
.Where
,.Find
, and.Any
:这是因为您没有为顶级查找指定合法的查找表达式。
我在这里展示一下:
那么你最初发现的条件是什么?
That's because you haven't specified a legitimate Find expression for your top level Find.
I'll show it here:
So what is the condition for your initial find?
最简单的一种是
没有任何空检查
The easiest one would be
without any null check