如何从源列表映射到其他目标列表

时间:2018-06-28 07:20:26

标签: c# linq

给出以下源类:

public class Product
{
    public ICollection<ProductColor> Colors {get; set;}
}

public class ProductColor
{
    public ColorEnum Color {get; set;}
}

以及以下目标类别:

public class ColorClass
{
    public ColorEnum Color {get; set;}
    public ICollection<Product> Products {get; set;}
}

如何使用LINQ从源到目标映射(复制)?

2 个答案:

答案 0 :(得分:1)

通过展平集合并按颜色重新分组,以下方法应该起作用:

Products.SelectMany(product =>
    product.Colors.Select(color => new { product, color })).
         GroupBy(entry => entry.color.Color). // entry.color is a ProductColor
         Select(group => new Color()
         {
           Color = group.Key,
           Products = group.Select(entry => entry.product).ToList()
         })

答案 1 :(得分:0)

.catch()
相关问题