C# Linq使用group by获取总计
我有以下课程:C# Linq使用group by获取总计,c#,linq,sum,C#,Linq,Sum,我有以下课程: class Item { public decimal TransactionValue { get; set; } public string TransactionType { get; set; } } 我有以下清单: var items = new List<Item> { new Item { TransactionValue =
class Item
{
public decimal TransactionValue { get; set; }
public string TransactionType { get; set; }
}
我有以下清单:
var items = new List<Item>
{
new Item
{
TransactionValue = 10,
TransactionType = "Income"
},
new Item
{
TransactionValue = 10,
TransactionType = "Income"
},
new Item
{
TransactionValue = -5,
TransactionType = "Outgoing"
},
new Item
{
TransactionValue = -20,
TransactionType = "Outgoing"
}
};
谢谢我相信使用Linq在一行中实现这一点可能有一种聪明的方法,但我能想到的一切都很难看,所以我选择了更具可读性的方法
var results = items.GroupBy(x => x.TransactionType)
.ToDictionary(x => x.Key, x => x.Sum(y => y.TransactionValue));
var totals = new Totals
{
TotalIncoming = results["Income"],
TotalOutgoing = results["Outgoing"]
};
您可以通过以下查询获得所需的结果:-
Totals result = new Totals
{
TotalIncoming = items.Where(x => x.TransactionType == "Income")
.Sum(x => x.TransactionValue),
TotalOutgoing = items.Where(x => x.TransactionType == "Outgoing")
.Sum(x => x.TransactionValue)
};
但是,正如您在类型Totals
中所看到的,我们需要对TransactionType进行硬编码,并且从结果中我们没有任何线索表明,除了使用的命名约定之外,此总和属于哪种类型
我将改为创建以下类型:-
class ItemTotals
{
public string ItemType { get; set; }
public decimal Total { get; set; }
}
在这里,我们将在结果中显示TransactionType及其相应的总计,我们可以简单地按TransactionType
分组并计算总和,下面是相同的查询:-
List<ItemTotals> query = items.GroupBy(x => x.TransactionType)
.Select(x => new ItemTotals
{
ItemType = x.Key,
Total = x.Sum(z => z.TransactionValue)
}).ToList();
List query=items.GroupBy(x=>x.TransactionType)
.选择(x=>new ItemTotals
{
ItemType=x.键,
总计=x.Sum(z=>z.TransactionValue)
}).ToList();
这是完整的,您可以从两者中进行选择。
var query=item.GroupBy(item=>item.TransactionType)。选择(grp=>new{Key=grp.Key,Total=grp.Sum(r=>r.TransactionValue)})代码>请参见:,如果不重复,则相关
List<ItemTotals> query = items.GroupBy(x => x.TransactionType)
.Select(x => new ItemTotals
{
ItemType = x.Key,
Total = x.Sum(z => z.TransactionValue)
}).ToList();