我有一个像下面提到的表
ID Group Dept Percentage
1 Science H2 100
2 History Y5 0
2 History Y5 50
2 History Y6 100
3 Econimcs E9 100
现在下面的代码将检查ID的和是0还是100。但是现在我需要将Group
和Dept
列包含到ID列中来检查和。var resultPCT = from row in dtNewL3.AsEnumerable()
group row by row["ID"]
into g
select new
{
Code = g.Key,
NewPCT = g.Sum(x => int.Parse(x["Percentage"].ToString()))
};
var errorPCT = resultPCT.Where(x => x.NewPCT != 100 && x.NewPCT != 0);
if (errorPCT.Any())
{
var CC = errorPCT.Select(x => x.Code);
string strAlert = string.Format("ID(s) {0} should have sum of 0 or 100 in Percentage.", string.Join(",", CC));
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('" + strAlert + "')", true);
return;
}
考虑到上面的表,这段代码将给出一个警告,说明ID 2的和不是0或100。
以上代码将仅根据ID检查0或100的和。但现在我需要检查和0或100将ID,Group &部门在一起。在上面的表中,现在ID - 2
, Group History
和Dept - Y5
应该弹出一个警告,说明它的和不是0或100。
您需要按多列分组,因此在第二行中可以这样做
group row by new { row["ID"], row["Group"], row["Dept"] }
因为您的键是多列的,所以还需要将errorPCT行更改为
var CC = errorPCT.Select(x => x.Group + " - " + x.Dept);
试试这个
var resultPCT = from row in dtNewL3.AsEnumerable()
group row by row["ID"]
into g
select new
{
Group = g.FirstOrDefault().Field<string>("Group"),
Dept = g.FirstOrDefault().Field<string>("Dept"),
CommCode = g.Key,
NewPCT = g.Sum(x => int.Parse(x["Percentage"].ToString()))
};