Fluent LINQ - select a parent list that contains a list of children with a subset of children

This title is the worst ...

In any case, I'm trying to select a parent that contains n number of children. I will pass a list of criteria (1..n) that the child objects must match. For brevity, here are the classes I'm working with:

public class Parent {

     public int Id { get; set; }

     public List<Child> Children { get; set; }

}

public class Child { 

    public int Id { get; set; }

    public int ParentId { get; set; }

    public int SomeValue { get; set; }

}

I am looking for a list of parents that contain children that match all SomeValues ​​that I pass

So, if I have:

Parent 1
    Child 1, SomeValue 10
    Child 2, SomeValue 20
    Child 3, SomeValue 40
Parent 2
    Child 4, SomeValue 10
    Child 5, SomeValue 20
    Child 5, SomeValue 50

and myList - [10, 50], it should return only parent 2. If myList [10, 20], then both parents should be returned. And finally, if myList [10, 20, 60], nothing needs to be returned.

, , , , , (?)

parents.where(p => p.children.all(c => myList.contains(c.SomeValue)));

, -, . , , myList. , , , myList.length, , SomeValue ( , SomeValues?)

+4
2

, Children:

var matches = parents.Where(p => myList.All(v => p.Children.Select(c => c.SomeValue).Contains(v)));
+8

, :

10,20
1
2
10,50
2

var parents = new List<Parent>
            {
                new Parent
                {
                    Id = 1,
                    Children =
                        new List<Child>
                        {
                            new Child {SomeValue = 10},
                            new Child {SomeValue = 20},
                            new Child {SomeValue = 40}
                        }
                },
                new Parent
                {
                    Id = 2,
                    Children =
                        new List<Child>
                        {
                            new Child {SomeValue = 10},
                            new Child {SomeValue = 20},
                            new Child {SomeValue = 50}
                        }
                }
            };

            var val1 = 10;
            var val2 = 20;
            var query = from a in parents
                from b in a.Children
                where b.SomeValue == val1
                select a;

            var query2 = from a in parents
                        from b in a.Children
                        where b.SomeValue == val2
                        select a;

            Console.WriteLine("10,20");
            foreach(var parent in query.ToList().Intersect(query2.ToList()))
                Console.WriteLine(parent.Id);

            val1 = 10;
            val2 = 50;

            Console.WriteLine("10,50");
            foreach (var parent in query.ToList().Intersect(query2.ToList()))
                Console.WriteLine(parent.Id);
0

All Articles