如何在 Linq 查询结果中检查 DBNull 值 [英] How to check DBNull value in Linq query results
本文介绍了如何在 Linq 查询结果中检查 DBNull 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用以下代码并尝试按货币和代码分组.在此之后,我尝试遍历结果集.
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.
但问题是在遍历结果时,最后我在 for each 语句中得到以下异常:
But the issue is while looping through the results, at the end I am getting the below exception on the for each statement:
对象不能从 DBNull 转换为其他类型.
DataTable dt = new DataTable();
var result = from r in dt.AsEnumerable()
result r by new
{
currency = r.Field<String>("CURRENCY"),
Code = r.Field<String>("CODE")
}
into grp
select new
{
currency = grp.Key.currency,
Code = grp.Key.Code,
amount = grp.Sum(x => Convert.ToDouble(x["AMOUNT"]))
};
foreach (var obj in result)
{
String sCurr =obj.currency;
String Code = obj.Code;
string amount= obj.amount.ToString());
}
请帮我解决这个问题.
推荐答案
类似的东西
amount = grp.Sum(x => Convert.ToDouble(x["AMOUNT"] == DBNull.Value ? 0 : x["AMOUNT"]));
如果那是给您带来问题的线路.
If that is the line that is giving you the problem.
这篇关于如何在 Linq 查询结果中检查 DBNull 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文