使用Linq合并两个列表

时间:2016-02-09 20:20:47

标签: c# .net linq

我有三个这样的模型:

public class Section
{
  public string Id {get; set;}

  public SubSection[] SubSections {get; set;}

  public Item[] Items {get; set;}
}

public class SubSection
{
  public string Id {get; set;}

  public string sectionId {get; set;}

  public Item[] Items {get; set;}
}

public class Item
{
  public string Id {get; set;}

  public string sectionId {get; set;}
}

现在当我得到结果时,我得到了章节和项目列表,并希望将这两个列表合并到上面的模型中。

所有内容都与部分ID相关联;确定项目在SubSection或直接在部分下的位置,子部分在部分数组下。

使用Linq有一个很好的方法吗?

示例:

Item { id = "123", sectionId = "456"}
Item {id = "234", sectionId = "786"}

SubSection {id = "211", sectionId = "786", Items = null}
SubSection {id = "210", sectionId = 456", Items[] = new Item() {"123"}}

Section {id = 786, subsections[] = null, items[] =  new Item() {"234" }}
Section {id = 456, subsection[] = new SubSection { id = 210}, items = null}

2 个答案:

答案 0 :(得分:1)

LINQ擅长阅读和转换,但不是修改它们所处的项目。它是可行的(正确的方式和“错误的”方式),但除非你特别需要,我会专注于你在这里问的问题。

List<SectionWithoutCollections> sections;
List<SubSectionWithoutCollections> subSections;
List<Item> items;

var subSectionsWithItems = subSections
    .GroupJoin(items, a => a.Id, b => b.SectionId, (a,b) => new SubSection
               {
                   Id = a.Id,
                   SectionId = a.SectionId,
                   Items = b.ToArray()
               });

var sectionsWithItems = sections
    .GroupJoin(subSectionsWithItems, a => a.Id, b => b.SectionId, (a,b) => new { Section = a, SubSections = b })
    .GroupJoin(items, a => a.Section.Id, b => b.SectionId, (a,b) => new Section
               {
                   Id = a.Section.Id,
                   Items = b.ToArray(),
                   SubSections = a.SubSections.ToArray()
               });

我分两步完成了这项工作,但如果可读性无关紧要(总是如此),你可以在一个步骤中完成。

一旦你知道这些方法,它就非常简单,但基本上我将所有的子部分和项目放在一起,然后我将所有的部分和子部分放在一起,然后我将所有的部分和子部分和项目放在一起。 / p>

请注意,任何孤立的项目或子项目(即那些没有SectionId的部分或子部分的项目或子项目都将被抛弃)。但无论如何,那是关系不好的,所以这是可以接受的,据我所知。

答案 1 :(得分:0)

var sections = new List<Section>();
        var subSections = new List<SubSection>();
        var items = new List<Item>();

        var itemSections = from s in sections
                           let i = items.Where(j => j.sectionId == s.Id).DefaultIfEmpty().ToArray()
                           let ss = subSections.Where(j => j.sectionId == s.Id).DefaultIfEmpty().ToArray()

                           select new Section
                           {
                               Id = s.Id,
                               SubSections = ss,
                               Items = i
                           };

这应该有效,尚未经过测试。不确定你是什么意思Merge tho

相关问题