C # Complex Linq - how to get objects whose identifiers or children ids match

Say I have the following structure,

public class Parent
{
 public string Id{get;set;}
 public string Name{get;set;}
 public List<Child> Children{get;set;}
}

public class Child{
 public string Id{get;set;}
 public string Name{get;set;}
}

and I have a list of strings containing identifiers List<string>Idsand a list of Parents List<Parent> parents. How can I filter my parents to get only the following:

  • Parent whose Id is contained in identifiers along with all child elements.
  • Only a child whose id is contained in the ids along with his parent.

So, if the identifiers contain the identifier of the parent, I want it with the children, and if it contains the child identifier, I want it with my parent (without the rest of the children).

, , , , , .

parents
  .Where(p => ids.Contains(p.Id) ||  
              p.Children.Any(x=>ids.Contains(x.Id)))
  .Select(res => new Parent() {  
     Name     = res.Name,
     Id       = res.Id,
     Children = es.Children
       .Where(child => ids.Contains(child.Id))
       .ToList()
   });
+4
2

, .

var result = parents
            .Where(p => ids.Contains(p.Id) || p.Children.Any(x => ids.Contains(x.Id)))
            .Select(res => new Parent() 
                { Name = res.Name, 
                  Id = res.Id, 
                  Children =  res.Children.Any(c => ids.Contains(c.Id)) && !ids.Contains(res.Id) 
                                                ? res.Children.Where(child => ids.Contains(child.Id)).ToList() 
                                                : res.Children.ToList() })
            .ToList();
+2

           string[] ids = parents.Select(x => x.Children.Select(y => y.Id)).SelectMany(x => x).OrderBy(x => x).Distinct().ToArray();

            Dictionary<string, List<Parent>> dict = new Dictionary<string, List<Parent>>();

            foreach (string id in ids)
            {
                List<Parent> parentId = parents.Where(x => x.Children.Any(y => y.Id == id)).ToList();
                dict.Add(id, parentId);
            }
+1

Source: https://habr.com/ru/post/1695643/


All Articles