有类似的问题,但我找不到解决方案.我有一个非常简单的对象定义.我需要一个返回按标签分组的金额总和的查询.
预期产出:
TagName Sum -------------------- Entertainment 70.00 Car 20.00 Travel 24.65
帐户类:
public string AccountName {get;set;} public ListTransactions {get;set;}
样本帐户:我的钱包
交易类:
public decimal Amount {get;set;} public ListTags{get;set;}
样本交易:10 , [Entertainment, Travel, Car]
标签类
public string Title {get;set;}
样本标签:Entertainment, Travel, Car, Food, Beverage
我希望它很清楚.我无法使用LINQ.我需要帮助
将每个事务计划为{ Amount, Title }
对象序列.然后按标记对这些对象进行分组,并计算每个组的金额总和:
account.Transactions .SelectMany(t => t.Tags.Select(tag => new { t.Amount, tag.Title })) .GroupBy(tagAmount => tagAmount.Title) .Select(g => new { TagName = g.Key, Sum = g.Sum(tagAmount => tagAmount.Amount) });
注意:此解决方案假定您在事务中没有重复的标记.否则你应该Distinct()
在投射标签集合后添加调用.
与查询语法相同:
var query = from t in account.Transactions from tag in t.Tags select new { t.Amount, tag.Title } into tagAmount group tagAmount by tagAmount.Title into g select new { TagName = g.Key, Sum = g.Sum(tagAmount => tagAmount.Amount) };