2 回答
TA贡献1966条经验 获得超4个赞
你可以这样做
var list1 = new List<Product>()
{
new Product(){Key1 = "Key1", Key2 ="Key2", Count1 = 1, Count2 = 2},
new Product(){Key1 = "Key2", Key2 ="Key3", Count1 = 1, Count2 = 2}
};
var list2 = new List<Product>()
{
new Product(){Key1 = "Key1", Key2 ="Key2", Count1 = 6, Count2 = 8},
new Product(){Key1 = "Key2", Key2 ="Key3", Count1 = 10, Count2 = 12}
};
var result = list1.Concat(list2)
.GroupBy(x => new {x.Key1,x.Key2})
.Select(x => new
{
x.Key.Key1,
x.Key.Key2,
SumCount1 = x.Sum(y => y.Count1),
SumCount2 = x.Sum(y => y.Count2)
}).ToList();
输出
Key1, Key2, 7, 10
Key2, Key3, 11, 14
其他资源
将指定集合的元素添加到列表的末尾。
Enumerable.GroupBy方法(IEnumerable,Func,Func)
根据指定的键选择器功能对序列的元素进行分组,并使用指定的功能为每个组投影元素。
Enumerable.Concat方法(IEnumerable,IEnumerable)
连接两个序列。
TA贡献1799条经验 获得超6个赞
List<Product> lst1 = new List<Product>();
List<Product> lst2 = new List<Product>();
lst1.Add(new Product() {Key1 = "K1",Key2 ="K2", Count1 =1, Count2=2 });
lst1.Add(new Product() { Key1 = "K2", Key2 = "K3", Count1 = 3, Count2 = 4 });
lst2.Add(new Product() { Key1 = "K1", Key2 = "K2", Count1 = 5, Count2 = 6});
lst2.Add(new Product() { Key1 = "K2", Key2 = "K3", Count1 = 7, Count2 = 8 });
// Way 1
var l = lst1.Join(lst2, l1 => l1.Key1, l2 => l2.Key1,
(lt1, lt2) => new Product { Key1 = lt1.Key1, Key2 = lt1.Key2, Count1 = lt1.Count1 + lt2.Count1, Count2 = lt1.Count2 + lt2.Count2 } ).ToList() ;
// Way 2
var result = lst1.Join(lst2, x => new { x.Key1, x.Key2 },
y => new { y.Key1, y.Key2 }, (x, y) =>
new Product { Key1 = x.Key1, Key2 = x.Key2, Count1 = x.Count1 + y.Count1, Count2 = x.Count2 + y.Count2 }).ToList();
- 2 回答
- 0 关注
- 176 浏览
添加回答
举报