过滤列表基于 T 的每个实例包含的另一个列表
因此,我在一个列表中有一组对象,但该列表中的每个对象都包含另一个列表。
请考虑以下事项:
class Parent
{
public Parent(string parentName)
{
this.ParentName = parentName;
}
public string ParentName { get; set; }
public List<Child> Children { get; set; }
}
class Child
{
public Child(string name)
{
this.ChildName = name;
}
public string ChildName { get; set; }
}
根据应用程序的性质,父对象列表中的所有 Parent 对象都是唯一的。多个父母可以包含同一个孩子,我需要获取包含孩子 x 的父母。
因此,假设 ChildName 为“child1”的孩子同时属于 ParentName 为“parent1”和“parent5”的父母。如果集合中有 100 个父母,我只想获取 ChildName 为“child1”的 Child 的父母,
我更愿意使用 lambda 表达式来执行此操作,但我不知道从哪里开始,因为我不知道确实有很多使用它们的经验。是否可能,如果可以,正确的方法是什么?
So I have a collection of objects in one list, but each object in that list contains another list.
Consider the following:
class Parent
{
public Parent(string parentName)
{
this.ParentName = parentName;
}
public string ParentName { get; set; }
public List<Child> Children { get; set; }
}
class Child
{
public Child(string name)
{
this.ChildName = name;
}
public string ChildName { get; set; }
}
By the nature of the application, all Parent objects in the list of parents are unique. Multiple parents can contain the same child, and I need to get the parents that contain child x.
So, say the child with ChildName of "child1" belongs to both parents with ParentName of "parent1" and "parent5". If there are 100 parents in the collection, I want to get only the ones that have the Child with ChildName of "child1"
I would prefer to do this with a lambda expression but I'm not sure where to start as I don't really have to much experience using them. Is it possible, and if so, what is the correct approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果
Child
类通过实现IEquatable
定义了相等运算,则可以使用 lambda(Enumerable.Where
)轻松完成此操作> LINQ 方法和List.Contains
方法:您现在可以迭代
filtered
并执行业务逻辑。如果
Child
类没有显式定义的相等操作(这意味着它将使用引用相等规则而不是检查相同的ChildName
),那么您需要包含自己检查 lambda 中的“什么通过等于”:注意:当然还有许多其他方法可以执行上述操作,包括可能更容易阅读的方法
但是,这效率不高作为
Any
版本,即使它会产生相同的结果。在这两种情况下,lambda 非常“读起来像”它们想要做的事情:
ChildName == "child1"
If the
Child
class has defined an equality operation by implementingIEquatable<Child>
, you can do this easily by using a lambda, theEnumerable.Where
method of LINQ and theList.Contains
method:You can now iterate over
filtered
and perform your business logic.If the
Child
class does not have an equality operation explicitly defined (which means that it will use reference equality rules instead of checking for identicalChildName
), then you would need to include the "what passes for equal" check into the lambda yourself:Note: There are of course many other ways to do the above, including the possibly easier to read
However, this is not as efficient as the
Any
version even though it will produce the same results.In both cases, the lambdas very much "read like" what they are intended to do:
ChildName == "child1"
你可以这样做:
You can do it like this:
这样就可以了
This would do it