给出以下行:
Amount, Name, Id
Scenario 1: 100.00,ABC,101
-100.00,ABC,101
Scenario 2: 50.00,XYZ,123
-100.00,XYZ,123
我想仅在金额未总计为0.00金额时对行进行求和和分组。所以Linq查询应该返回:
Amount, Name, Id
Scenario 1: 100.00,ABC,101
-100.00,ABC,101
Scenario 2:-50.00,XYZ,123
到目前为止我所拥有的:
var results = dt.AsEnumerable().GroupBy(row => new
{
Name = row.Field<string>("NAME"),
Id = row.Field<int>("ID")
}).Select(grp =>
{
DataRow dr = dt.NewRow();
dr["AMOUNT"] = grp.Sum(r => r.Field<decimal>("AMOUNT"));
dr["NAME"] = grp.Key.Name;
dr["ID"] = grp.Key.Id;
return dr;
}).CopyToDataTable();
答案 0 :(得分:2)
您可以使用SelectMany
扩展程序尝试以下查询:
X
答案 1 :(得分:2)
很难理解你的要求,所以我假设你的意思是:
汇总和分组行,因此只列出任何给定ID的汇总事务,除非总数为零,然后列出该ID的所有事务。
这是一个工作示例,包含您提供的测试数据:
var amounts = new[]
{
new
{
Amount = 100.00m,
Name = "ABC",
Id = 101,
},
new
{
Amount = -100.00m,
Name = "ABC",
Id = 101,
},
new
{
Amount = 50.00m,
Name = "XYZ",
Id = 123,
},
new
{
Amount = -100.00m,
Name = "XYZ",
Id = 123,
},
};
// summarise everything
var summaries = from a in amounts
group a by new { a.Id, a.Name } into grouping
select new
{
Amount = grouping.Sum(g => g.Amount),
grouping.Key.Name,
grouping.Key.Id,
};
// get the ids of records we need the full audit log for
var zeroSummaries = summaries.Where(s => s.Amount == 0).Select(s => s.Id).ToList();
// concat the summarised records together with the ones we need the full audit log for
summaries = amounts.Where(a => zeroSummaries.Contains(a.Id))
.Concat(summaries.Where(s => s.Amount != 0));
这是输出: