【问题标题】:LINQ to intersect elements of complex List<T> into new List<T>LINQ 将复杂 List<T> 的元素相交到新 List<T>
【发布时间】:2020-05-23 16:21:43
【问题描述】:

我目前正在开发一个 .NET 4.7 应用程序。

Given 是 1 list,其中包含父元素和子元素。我需要根据父元素 ID 对列表中的所有元素进行分组。

这不是那么简单,因为我有一个复杂的类型对象:List&lt;LinkParentChildViewModel&gt;

public class LinkParentChildViewModel
{
    public Location Parent { get; set; }
    public List<LocationLink> Children { get; set; }
}

public class Location
{
   public int Id { get; set; }
   public string Name { get; set; }
}

public class LocationLink
{
   public int Id { get; set; }
   public int ParentId { get; set; }
   public int ChildId { get; set; }
}

好吧,给定的 List 可以包含多个具有相同 Id 但不同 Child 的 Parent 元素。

目前我需要在一个父元素下加入/分组所有具有相同父元素的子元素。

我开始了我的 LINQ 查询,但不知何故我卡住了:

var joined = (from a in LinksParentChild
    join b in LinksParentChild
        on a.Parent.Id equals b.Parent.Id
    select new LinkParentChildViewModel { Parent = a.Parent, Children = new List<LocationLink>
    {
        // ...
    } }).ToList();

你知道如何将列表的所有子元素与相同的父元素分组吗?

非常感谢!!

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    这是解决问题的方法:

    List<LinkParentChildViewModel> list = new List<LinkParentChildViewModel>();
    //List seed
    list = list.GroupBy(x => x.Parent.Id).Select(x => new LinkParentChildViewModel
    {
        Parent = x.First().Parent,
        Children = x.SelectMany(x => x.Children).ToList()
    }).ToList();
    

    我们在做什么:

    1) 我们将每个LinkParentChildViewModel 分组,按Parent.Id 分组

    2) 我们按照以下规则创建合并实体

    3) 对于每个组,取第一个项目的 Parent 并将其用作合并实体的 Parent,假设它应该对每个人都是平等的

    4) 对于每个组,将每个项目的Children 合并到一个列表中,并将其用作合并项目的Children。

    【讨论】:

    • 感谢 Marco,正是我想要的。祝你有美好的一天!
    • 这真的有效吗? list.GroupBy 中的 list 为空。除了一个空列表,它怎么能产生任何东西?
    • @AndrewR “list seed”代表“填写列表的说明”
    猜你喜欢
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-25
    • 1970-01-01
    • 2010-10-25
    • 1970-01-01
    相关资源
    最近更新 更多