指定的强制转换在foreach中无效 [英] Specified cast is not valid in foreach

查看:185
本文介绍了指定的强制转换在foreach中无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我尝试使用linq将类型及其severties分组到datatable

  var  query = 来自  dt_cv。 AsEnumerable()
group row by new {severity = row.Field< string>(< span class =code-string> 严重性),
type = row.Field< DateTime>( 键入)} into sev
select new
{
Type = sev.Key.type,
severity = sev.Key.severity,
sev_count = sev.Count()
};



当我试用为了在foreach循环中获取查询的值,它抛出'指定的强制转换无效'

  foreach  var  res  in  query)
{
dt.Rows.Add ( new object [] {res.Type,res.severity,res.sev_count});
}



请帮忙。



提前致谢

解决方案

正如Tomas所说,这是Linq查询中的强制转换导致问题。它出现在 foreach 中,因为Linq代码不会立即执行 - 它是延迟执行系统。当您尝试通过将查询结果包含在 foreach 表达式中作为目标来使用查询结果时,会导致查询被执行 - 因此执行转换操作作为的foreach



按照建议,检查你的数据类型 - 源数据表列,并确保将Type列转换为DateTime是有效的 - 我怀疑没有,给定它的名字!


首先,OriginalGriff是对的。

其次,我建议使用 CopyToDataTable() [ ^ ]方法改为 foreach 循环。

Hi All,

I trying to group types and its severties on datatable using linq

var query = from row in dt_cv.AsEnumerable()
             group row by new { severity = row.Field<string>("Severity"), 
                          type = row.Field<DateTime>("Type") } into sev
              select new
               {
                Type = sev.Key.type,
                severity = sev.Key.severity,
                sev_count = sev.Count()
               };


When I am trying to get the value of query in foreach loop, it is throwing 'Specified cast is not valid'

foreach (var res in query)
{
  dt.Rows.Add(new object[] { res.Type, res.severity, res.sev_count });
}


Please help.

Thanks in advance

解决方案

As Tomas says, it's the cast in your Linq query that causes the problem. It occurs in the foreach because Linq code is not executed immediately - it is a deferred execution system. When you try to use the query results by including it as a target in the foreach expression, that causes the query to be executed - and so the cast operations happen as part of the foreach.

So as suggested, check your datatypes - the source datatable columns and make sure that casting the "Type" column to a DateTime is valid - I would suspect not, given it's name!


First of all, OriginalGriff is right.
Secondly, i'd suggest to use CopyToDataTable()[^] method instead foreach loop.


这篇关于指定的强制转换在foreach中无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆