我有两个列表
List<Product> Products;
List<Showcase> Showcases;
Product class包含ShowcaseID,它是Showcase Class的ID值
和Showcase类一样;
public class Showcase
{
public int ID { get; set;}
//.....
public List<Product> Products { get; set; }
}
预期输出
List<Showcase> MergedList; // Same of Showcase class from beginning but contains All Product groupped by ShowcaseID
ofc我可以将这些对象与循环合并,但我想用Linq做,最简单的方法是什么?
答案 0 :(得分:0)
尝试列表的ForEach方法
https://msdn.microsoft.com/en-us/library/bwabdf9z(v=vs.110).aspx
List<Product> Products;
List<Showcase> Showcases;
Showcases.ForEach(s => s.Products.AddRange(Products.Where(p => p.ShowcaseID == s.ID)));
更新1
如果您不想丢失Showcases列表,可以使用以下内容。
List<Showcase> MergedList = new List<Showcase>();
MergedList.AddRange(Showcases.Select(s => new Showcase { Products = products.Where(p => p.ShowcaseID == s.ID).ToList() }));