在LINQ中分组导致空引用异常的数据表

时间:2013-11-25 10:33:46

标签: c# linq datatable

嗨我有一个没有问题的查询

 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'

2 个答案:

答案 0 :(得分: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()
        };   

答案 1 :(得分:1)

在使用Ternary运算符进行分组之前检查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()
        });

有关详情,请访问以下博客:

http://infinitecodex.com/post/2010/07/05/LINQ-Group-By-with-NULL-database-values.aspx