检查null并强制为0

时间:2012-08-02 13:54:27

标签: c# ado.net null

我从数据列返回一个整数列表。这个特定的列是(int,null)。 但我有一个例外。

Specified cast is not valid.

代码:

public List <int> GetSortOrder(DataTable dt,string columnName)
{
    List<int> Orders = new List<int>();
    foreach (DataRow row in dt.Rows)
    {
        Orders.Add((int)row[columnName]);
    }
    return Orders;
}

我想要的是它是否为null,然后将其强制为0。 我应该使用可空类型int吗?或者只是简单地使用if ... else ...?

5 个答案:

答案 0 :(得分:6)

        Orders.Add((int)(row[columnName] ?? 0));

答案 1 :(得分:3)

该列实际上存储了DBNull.Value而不是通常的C#null。这就是为什么运营商?不管用。要检查列是否为null,请使用row.IsNull方法:

Orders.Add(row.IsNull(columnName) ? 0 : (int)row[columnName]);

操作员?不适用于DBNulls。

您可能还想查看此链接:Handle DBNull in C#以获取将DBNull-able int转换为int的一些有效示例?

答案 2 :(得分:1)

我还会使用int吗?我喜欢Field方法:

int? myInt = row.Field<int?>(columnName);

答案 3 :(得分:0)

我建议int?

Orders.Add(((int?)row[columnName]).GetValueOrDefault());

在我看来,它保持了意图和代码的清晰和简洁,if / else做得不好。使用?? 0作为其他答案的建议也很好。

答案 4 :(得分:0)

这应该有效:

public List <int> GetSortOrder(DataTable dt,string columnName)
{
    List<int> Orders = new List<int>();
    int? nullableInt;
    foreach (DataRow row in dt.Rows)
    {
        nullableInt = (int)row[columnName];
        Orders.Add(nullableInt??0);
    }
    return Orders;
}