使用Linq

时间:2015-05-25 07:57:29

标签: c# asp.net .net linq

我有一张如下所述的表格

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之和。但现在我需要在ID列中包含GroupDept列以检查总和。

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 - 2Group History以及Dept - Y5的警告,说明它的总和不是0或100。

2 个答案:

答案 0 :(得分:1)

您需要按多列进行分组,因此在第二行中您可以执行此操作

group row by new { row["ID"], row["Group"], row["Dept"] }

由于您的密钥是多列,您还需要将errorPCT行更改为

var CC = errorPCT.Select(x => x.Group + " - " + x.Dept);

答案 1 :(得分:1)

试试这个

            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()))
                                };​