【问题标题】:Grouping datatable causing null reference exception in LINQ分组数据表导致 LINQ 中的空引用异常
【发布时间】:2019-06-26 13:46:25
【问题描述】:

您好,我有一个查询运行没有问题

 var v = (from r in cTable.AsEnumerable()
         group r by r.Field<string>("Name") into g
         select new
         {
            CallType = g.Key,
            Count = g.Count()
         });        

这运行得很好。但是当我通过添加进行更改时

 var v = (from r in cTable.AsEnumerable()
         group r by r.Field<string>("Name").Replace(",", "") into g
         select new
         {
            CallType = g.Key,
            Count = g.Count()
         });              

它给了我Object Refrenence not set to instance errror 为什么会这样?我只是想在分组数据时应避免名称列中的任何逗号,即“Rajeev”和 Ra,jeev 在分组时应计为“Rajeev”

【问题讨论】:

  • 那么strColumn 的值是多少?你确定在你测试的时候是Name吗?
  • 是的。我已经编辑了问题
  • 看起来至少有一个元素 r.Field&lt;string&gt;("Name") 为空。
  • @KingKing 肯定是这样,我如何在此处检查是否在分组数据时忽略空值

标签: c# linq datatable


【解决方案1】:

试试这个安全的解决方案:

var v = from r in cTable.AsEnumerable()
        let name = r.Field<string>("Name")
        group r by (name ?? "").Replace(",", "") into g
        select new {
          CallType = g.Key,
          Count = g.Count()
        };      

请注意,使用上面的代码,所有 null 或空字符串将被分组到同一个组中。如果你想过滤掉所有的空值,只需在这样的地方添加一些:

var v = from r in cTable.AsEnumerable()
        let name = r.Field<string>("Name")
        where name != null
        group r by name.Replace(",", "") into g
        select new {
          CallType = g.Key,
          Count = g.Count()
        };   

【讨论】:

  • Invalid Term or expression')'
  • @RajeevKumar 已更新,这是因为我复制了您的代码。只需删除最后一个 ) 之前的最后一个 ;
  • 现在好了。谢谢:)
【解决方案2】:

在使用三元运算符分组之前检查 Null,您可以将 null 替换为一些字符串,例如" 或空字符串,无论您想使用什么术语来显示空组键

var v = (from r in cTable.AsEnumerable()
        group r by r.Field<string>("Name") == null ? "<null>" : r.Field<string>("Name").Replace(",", "") into g
        select new
        {
           CallType = g.Key,
           Count = g.Count()
        });

更多详情请查看以下博客:

https://web.archive.org/web/20110521014654/http://infinitecodex.com/post/2010/07/05/LINQ-Group-By-with-NULL-database-values.aspx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 2011-01-25
    • 1970-01-01
    相关资源
    最近更新 更多