最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - Dynamic LINQ struggling to manage DBNull value in Sum with Group By (in Datatable) - Stack Overflow

programmeradmin2浏览0评论

I'm using a dynamic linq on the DataTable to generate consolidated summations. All everything works great except when a value is null for Column9 used for summation. I got NullException ''Object cannot be cast from DBNull to other types.''. All these columns are dynamically selected by users, including the column for sum.

public bool CreateConsolidation(string sum_Column) // e.g. Column9 will pass as sum_Column
{
      var sum_str =  "Sum(Convert.ToInt32(" + sum_Column + ")) as " + sum_Column;

      var double_grouping = (dt_excel.AsEnumerable().AsQueryable()
                            .GroupBy("new (it.Column4, it.Column5, it.Column6,   it.Column7, it.Column11 )", "it"))
                            .Select("new (Key.Column4 as Column4, Key.Column5 as Column5, Key.Column6 as Column6, Key.Column7 as Column7, Key.Column11 as Column11, Sum(new ( " + sum_str + " )) as QTY )").ToDynamicList();

      //have to perform some other operations based on above result

      return true;
}

Is there any way to check this null value for this dynamic linq Query?

And I want the result is something like below. the first line must check the DBNull Value.

public bool CreateConsolidation(string sum_Column) // e.g. Column9 will pass as sum_Column
{
      var sum_str =  "Sum(it." + sum_Column + " == DBNull.Value ?  : Convert.ToInt32(it." + sum_Column + ")) as " + sum_Column;

      var double_grouping = (dt_excel.AsEnumerable().AsQueryable()
                            .GroupBy("new (it.Column4, it.Column5, it.Column6,   it.Column7, it.Column11 )", "it"))
                            .Select("new (Key.Column4 as Column4, Key.Column5 as Column5, Key.Column6 as Column6, Key.Column7 as Column7, Key.Column11 as Column11, Sum(new ( " + sum_str + " )) as QTY )").ToDynamicList();

      //have to perform some other operations based on above result

      return true;
}
发布评论

评论列表(0)

  1. 暂无评论