Linq Enumerable with Grouping和Aggregate into datatable或list

时间:2018-03-17 12:57:31

标签: c# linq

尝试使用LINQ根据组聚合检索记录,并将结果放入数据表中。

表格(名称:rstable)

RSNo        Type
------------------
Rs01      |  1  |     
Rs02      |  5  |   
Rs01      |  2  |  
Rs01      |  1  |  
Rs02      |  5  |  
Rs02      |  5  |  
Rs01      |  2  |  
Rs02      |  5  |      
------------------ 

Sql命令和输出:

select rsno,type,count(type) as cnt from rstable group by rsno,type

rsno   type   cnt
-----------------
Rs01     1     2
Rs01     2     2
Rs02     5     4
-----------------  

尝试使用LINQ:

Have created a datatable :

DataTable dttypes = new DataTable();
dttypes.Columns.Add("rsno", typeof(String));
dttypes.Columns.Add("type", typeof(int));
dttypes.Columns.Add("cnt", typeof(int));

这里dtresrep是一个数据表,它保存sql表中的条目

var typeinfo = from typerow in dtresrep.AsEnumerable()
               group 1 by 
                     new { 
                             rsno = typerow.Field<String>("rsno"), 
                             type  = typerow.Field<int>("type") 
                         } into typegrp
               select new { 
                            typegrp.Key.rsno, 
                            typegrp.Key.type, 
                            cnt = typegrp.Count() 
                          };

然后尝试投入数据表。

foreach (var t in typeinfo)
    dttypes.Rows.Add(t.rsno, t.type, t.cnt);

这会引发Cast异常。 “Specified Cast无效。”请指导。

1 个答案:

答案 0 :(得分:1)

它应该是这样的,因为它的[System.InvalidCastException] = {"Specified cast is not valid."}错误与DataBase和.net moslty之间的类型不匹配有关,在这种情况下它与integer类型

有关
var typeinfo = (from typerow in dtresrep.AsEnumerable()
                 group typerow by 
                 new { 
                      resno = typerow["resno"] == DBNull.Value ? '' : typerow["resno"].toString() , 
                      type  = Convert.ToInt32(typerow["type"] == DBNull.Value ? 0 : typerow["type"]) 
                     } 
                    into typegrp
                    select new { 
                            typegrp.Key.resno, 
                            typegrp.Key.type, 
                            cnt = typegrp.Count() 
                          }).ToList();

为了在数据表代码中添加新行,shold就像

DataTable dttypes = new DataTable();
dttypes.Columns.Add("rsno", typeof(String));
dttypes.Columns.Add("type", typeof(int));
dttypes.Columns.Add("cnt", typeof(int));

foreach (var t in typeinfo)
{
  //you need to add row like this i.e. by calling NewRow() method
  //this can be issue in you code 
    row = dttypes.NewRow();
    row["rsno"] = t.rsno;
    row["type"] = t.type;
    row["cnt"] = t.cnt;
    dttypes.Rows.Add(row);
}