【发布时间】:2018-03-19 14:08:06
【问题描述】:
尝试使用 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 异常。 “指定的演员表无效。”请指导。
【问题讨论】:
-
包含异常信息。
-
[System.InvalidCastException] = {"指定的强制转换无效。"}