[英]Merge two lists using 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中或在section下的直接位置,以及subsection在section數組下的位置。
有使用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}
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()
});
我分兩步進行了此操作,但是如果可讀性無關緊要,那么您可以一步完成(總是如此)。
一旦知道了方法,這將非常簡單,但是基本上我將所有小節和小項放在一起,然后將所有小節和小節放在一起,然后將所有小節和小項放在一起。
請注意,任何孤立的項目或小節(即不存在帶有SectionId
小節或小節的項目)將被丟棄。 但是無論如何,這種關系不好,據我所知,這是可以接受的。
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
};
這應該工作,未經測試。 不知道您所說的是什么意思
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.