我有一个类型为TaxDetails类的列表
public class TaxDetails
{
public string ID {get; set;}
public string ItemID {get; set;}
public string TaxID {get; set;}
public string TaxCode {get; set;}
public decimal TaxAmount {get; set;}
}
可以有许多具有相同税号的商品,但ID不会重复。我需要返回一个包含Tax id及其总和的Dictionary。这意味着在获得金额时,它应该按税号
分组Dictionary<string,decimal> taxSums
此词典仅包含列表中该特定出租人的税号及其总税额。
答案 0 :(得分:3)
这应该有效:
var result =
list
.GroupBy(x => x.TaxID) //Group by TaxID
//Convert to dictionary. The key is the TaxID
//and the value is the sum of tax amount values in the individual group
.ToDictionary(g => g.Key, g => g.Sum(x => x.TaxAmount));
答案 1 :(得分:1)
小组然后总结他们。然后将结果扔到字典中。
var taxSums = context.TaxDetails.GroupBy(d => d.TaxID, d => d.TaxAmount)
.ToDictionary(g => g.Key, g => g.Sum());