有没有办法检查PREM_A或PREM_B的总和在同一LINQ查询中是不是0,而不是在单独的LINQ查询中,如下面的那个,即matchRows?
var resultsDt = dt.AsEnumerable().GroupBy(row => new
{
Id = row.Field<string>("ID")
}).Select(grp =>
{
DataRow newRow = dt.NewRow();
newRow["ID"] = grp.Key.Id.Trim();
newRow["PREM_A"] = grp.Sum(r => r.Field<decimal>("PREM_A"));
newRow["PREM_B"] = grp.Sum(r => r.Field<decimal>("PREM_B"));
return newRow;
}).CopyToDataTable();
var matchRows = resultsDt.Select().Where(x => x.Field<decimal>("PREM_A") != 0 || x.Field<decimal>("PREM_B") != 0);
foreach (DataRow row in matchRows)
{
//do something
}
答案 0 :(得分:1)
您不需要为每一步转换为数据表,如果您离开它,将更容易查询。
var query =
from row in dt.AsEnumerable()
group new
{
premA = row.Field<decimal>("PREM_A"),
premB = row.Field<decimal>("PREM_B"),
} by row.Field<string>("ID").Trim() into g
let premA = g.Sum(x => x.premA)
let premB = g.Sum(x => x.premB)
where premA != 0M || premB != 0M
select new
{
Id = g.Key,
PremA = premA,
PremB = premB,
};
答案 1 :(得分:0)
此外:
var resultsDt = dt.AsEnumerable()
.GroupBy(row => row.Field<string>("ID"))
.Select(grp =>new {Id= grp.Key,
PREM_A= grp.Sum(r => r.Field<decimal>("PREM_A")),
PREM_B=grp.Sum(r => r.Field<decimal>("PREM_B"))
})
.Where(e=>e.PREM_A!=0 || e.PREM_B!=0);