How to check DBNull value in Linq query results

前端 未结 4 1333
耶瑟儿~
耶瑟儿~ 2020-12-10 08:59

I am using the below code and trying to group by Currency and Code. After this I am trying to loop through the result set.

But the issue is while looping through the

相关标签:
4条回答
  • 2020-12-10 09:39

    This:

    amount = grp.Sum(x => Convert.ToDouble(x["AMOUNT"]))
    

    will not work as you expect. If x["AMOUNT"] is DBNull.Value instead of a valid double, the conversion will fail with an exception. Instead, try:

    amount = grp.Sum(x.Field("AMOUNT"))

    if you expect that field to be a double. Sum will treat the null values as zero, per MSDN.

    0 讨论(0)
  • 2020-12-10 09:52

    I'm not sure which one is getting the error, but you can can compare it to DBNull.Value like so.

    String sCurr = obj.currency == DBNull.Value ? "" : obj.currency;
    
    0 讨论(0)
  • 2020-12-10 09:56

    Something like

     amount = grp.Sum(x => Convert.ToDouble(x["AMOUNT"] == DBNull.Value ? 0 : x["AMOUNT"]));
    

    If that is the line that is giving you the problem.

    0 讨论(0)
  • 2020-12-10 09:58

    The way to find the number of CELLS with DBNulls for a specific column:

    int numOfEmptyColA = MyDataTable.AsEnumerable().Where(p=>p.IsNull("ColA")).Count();
    
    0 讨论(0)
提交回复
热议问题