我有以下LINQ查询,它创建以下输出:
var query = from s in db.Sku
join sc in db.SkuCombo on s.Sku equals sc.Sku
join s2 in db.Sku on sc.SkuId equals s2.Sku
where skulist.Contains(s.Sku)
select new
{
Sku = s.Sku,
SkuQty = s.SkuQty,
ComboSku = s2.Sku,
ComboSkuQty = sc.Qty
};
Sku SkuQty ComboSku ComboSkuQty
===============================================
ABC-123 1 CCC-111 2
ABC-123 1 DDD-222 3
ABC-123 1 EEE-333 1
ABC-123 1 FFF-444 4
XYZ-789 3 JJJ-777 5
XYZ-789 3 KKK-888 1
我希望将输出映射到C#类OrderItem
,但是我不确定该怎么做。我很确定我需要在group by
上使用Sku
吗?
public class OrderItem
{
public string Sku { get; set; }
public int SkuQty { get; set; }
public List<ComboItem> ComboItems { get; set; }
}
public class ComboItem
{
public string ComboSku { get; set; }
public int ComboSkuQty { get; set; }
}
答案 0 :(得分:1)
尝试以下操作:
var query = (from s in db.Sku
join sc in db.SkuCombo on s.Sku equals sc.Sku
join s2 in db.Sku on sc.SkuId equals s2.Sku
where skulist.Contains(s.Sku)
select new
{
Sku = s.Sku,
SkuQty = s.SkuQty,
ComboSku = s2.Sku,
ComboSkuQty = sc.Qty
}).GroupBy(x => x.Sku)
.Select(x => new OrderItem()
{
Sku = x.Key,
SkuQty = x.Sum(y => y.SkuQty),
ComboItems = x.Select(y => new ComboItem()
{
ComboSku = y.ComboSku,
ComboSkuQty = y.ComboSkuQty
}).ToList()
}).ToList();