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?
If the
Childclass has defined an equality operation by implementingIEquatable<Child>, you can do this easily by using a lambda, theEnumerable.Wheremethod of LINQ and theList.Containsmethod:You can now iterate over
filteredand perform your business logic.If the
Childclass 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
Anyversion 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"