我有两个列表,其中包含1列货币和总计,如
list1
Currency Total
USD 10
EUR 25
list2
Currency Total
USD 10
EUR 25
INR 55
如何从基于货币基础的单个列表中的两个列表中获得总和,如此
ListSummary
Currency Total
USD 20
EUR 50
INR 55
以下Linq代码为我生成了2个列表
var license_sum = licenses.GroupBy(x => x.Currency,
(key, values) => new {
Currency = key,
Total = values.Sum(x => x.FeesCustom == 0 ? x.FeesNormal : x.FeesCustom)
});
var trans_sum = translations.GroupBy(x => x.Currency,
(key, values) => new {
Currency = key,
Total = values.Sum(x => x.FeesCustom == 0 ? x.FeesNormal : x.FeesCustom)
});
从这2个我正在计划overool_sum列表
答案 0 :(得分:1)
var overool_sum = licenses.Concat(translations).GroupBy(x => x.Currency,
(key, values) => new {
Currency = key,
Total = values.Sum(x => x.FeesCustom == 0 ? x.FeesNormal : x.FeesCustom)
});
如果它们是相同的类型 - 否则只是.Select
一个常见的类型: - )
答案 1 :(得分:1)
这应该适合你:
class MyClass {
public string Currency { get; set; }
public decimal Total { get; set; }
}
void Main() {
var list1 = new List<MyClass>(){
new MyClass{ Currency = "USD" , Total = 10},
new MyClass{ Currency = "EUR" , Total = 25},
};
var list2 = new List<MyClass>(){
new MyClass{ Currency = "USD" , Total = 10},
new MyClass{ Currency = "EUR" , Total = 25},
new MyClass{ Currency = "INR" , Total = 55},
};
var list3 = list1.Concat(list2);
var list4 = list3.GroupBy(x => x.Currency).Select(y => new MyClass {
Currency = y.Key,
Total = y.Sum(z => z.Total)
});
Console.WriteLine(list4);
}
答案 2 :(得分:1)
您可以使用Concat
linq扩展名来连接两个列表,然后使用GroupBy
对当前列表进行分组..
var overool_sum = license_sum.Concat(trans_sum )
.GroupBy(x => x.Currency)
.Select(x=> new
{
Currency = x.Key,
Total = x.Sum(x => x.Total)
})
.ToList();