简体   繁体   English

合并父母名单和孩子名单

[英]Combine list of parents with list of children

Is there a way using Linq to combine a list of parent objects with a list of children objects so the parent list includes the children with the same ids? 有没有一种使用Linq的方法将父对象列表与子对象列表组合在一起,以便父列表包括具有相同ID的子对象?

I have a list of parents with no children populated and a separate list of children and want to combine them so the list of parents has the children included with the appropriate parent. 我有一个没有孩子的父母名单,还有一个单独的孩子名单,并希望将它们合并在一起,因此父母名单中有适当的父母包括的孩子。

public class Parent
{
    public int Id { get; set; }
    public virtual List<Children> Children { get; set; }
}

public class Children
{
    public int Id { get; set; }
    public int ParentId { get; set; }
}

If I understand correctly you have two lists as follows: 如果我理解正确,您将有两个列表,如下所示:

List<Parent> parents;
List<Children> children;

You can then join the parents with the children, to create new Parent objects that have the children attached: 然后,您可以将父母与孩子一起加入,以创建附加了孩子的新Parent对象:

var newParents = parents.GroupJoin(
     children, 
     parent => parent.Id, 
     child => child.ParentId, 
     (parent, children) => new Parent { Id = parent.Id, Children = children.ToList() });

If your list of parents already exists, you don't want to do this entirely in LINQ. 如果您的父母名单已经存在,则您不希望在LINQ中完全这样做。 We'll use LINQ to group the children with siblings, then loop over that conventionally and assign to the parents' Children properties. 我们将使用LINQ将孩子与兄弟姐妹分组,然后按常规遍历并分配给父母的Children属性。 If there's enough parents for the lookup to be an efficiency issue, you should put them in a dictionary. 如果有足够多的父母希望查找效率问题,则应将其放入词典中。

foreach (var g in children.GroupBy(ch => ch.ParentId))
{
    //  Use Single() rather than FirstOrDefault() if orphans are forbidden.
    //  It will throw an exception if no match is found. 
    var parent = parents.FirstOrDefault(p => p.Id == g.Key);

    if (parent != null)
    {
        parent.Children = g.ToList();
    }
}

The legitimate pure-LINQ option, as Tim notes, is to create new Parent objects. 正如Tim所指出的那样,合法的pure-LINQ选项是创建新的Parent对象。 Nothing wrong with that. 没有错。 What you don't want to do is write a LINQ query that alters the input objects. 您不想做的是编写一个LINQ查询来更改输入对象。 That generally ends in tears. 那通常以眼泪结束。 The above pattern gets used in code where I work because we have large POCO classes with many properties and no existing need for copy constructors. 上面的模式用在我工作的代码中,因为我们有带有许多属性的大型POCO类,并且不需要复制构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM