【问题标题】:Object cannot be cast from DBNull to other types Linq对象不能从 DBNull 转换为其他类型 Linq
【发布时间】:2018-12-21 06:03:13
【问题描述】:

我面临错误 Object cannot be cast from DBNull to other types.

我尝试引入空值,即使得到相同的 DBNull 错误。如何处理这个错误?

List<string> List = new List<string>();
 List = (from r in Dt.AsEnumerable()
                                 orderby Convert.ToDateTime(r["StartDate"]) descending
                                                select r["name"] + string.Empty).ToList();

【问题讨论】:

    标签: c# linq datatable enumerable


    【解决方案1】:

    没问题。以下代码将解决您的问题,不需要额外的方法,并且与 Mark Gravell 的解决方案不同,它处理 r["name"]。

    var list = new List<string>();
    list = (from r in Dt.AsEnumerable()
        orderby Convert.ToDateTime(r["StartDate"] == DBNull.Value ? "1/1/1" : r["StartDate"].ToString()) descending
        select (r["name"] == DBNull.Value ? string.Empty : r["name"].ToString())).ToList();
    

    1/1/0001 是日期时间的默认值。因此,如果 r["StartDate"] == DBNull.Value,则表达式的计算结果与 "new DateTime()" 的值相同。

    祝你好运!

    【讨论】:

    • coalesce 仅适用于“真实”null - OP 在问题中明确提及 DBNull;合并对DBNull 值没有帮助
    【解决方案2】:

    由于您正在处理 LINQ-to-Objects,您可以使用自己的自定义转换,可能类似于:

    static DateTime? CustomParseDateTime(object value) {
        if(value == null || value is DBNull) return null;
        return Convert.ToDateTime(value);
    }
    

    orderby CustomParseDateTime(r["StartDate"])
    

    【讨论】:

    • 谢谢。您认为发生错误是因为 startDate 问题吗?
    • @ShakeerHussain 定义“问题”?如果其中一些没有定义的值,那么...确定吗?
    • 名称具有空值,此代码不会删除空值 * where r["name"].ToString() != "" && r["name"] != DBNull.Value跨度>
    猜你喜欢
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多