C# Filer DataTable 排除 DBNull.Value
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/762000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Filer DataTable to exclude DBNull.Value
提问by Sergey
I receive a DataTable from excel file and data in the first Column looks like this:
我从 excel 文件中收到一个数据表,第一列中的数据如下所示:
11129
11129
DBNull.Value
DBNull.Value
29299
29299
29020
29020
DBNull.Value
DBNull.Value
29020
29020
I'm using LINQ to select distict and it works if there are no DBNull.Value values as below. albumIds = dt.AsEnumerable().Select(p => (int)p.Field("F1")).Distinct().ToArray();
我正在使用 LINQ 来选择 distict,如果没有如下所示的 DBNull.Value 值,它就可以工作。专辑Ids = dt.AsEnumerable().Select(p => (int)p.Field("F1")).Distinct().ToArray();
But if DBNull.Value present which represent empty excel cells I get conversion errors.
但是如果 DBNull.Value 存在代表空的 excel 单元格,我会收到转换错误。
How do I filter out those DBNull.Value from my result set?
如何从结果集中过滤掉那些 DBNull.Value?
Thank you
谢谢
采纳答案by Joel Mueller
As hinted at in Jeremy's answer, If you've a reference to System.Data.DataSetExtensions.dll, you'll get some handy extension methods for working with DataSets and DataTables using LINQ. Specifically, you can use the Field<int?>
() method to convert an integer column that might contain DBNull into a column of nullable ints...
正如 Jeremy 的回答所暗示的那样,如果您有对System.Data.DataSetExtensions.dll的引用,您将获得一些使用 LINQ 处理数据集和数据表的方便的扩展方法。具体来说,您可以使用 Field <int?>
() 方法将可能包含 DBNull 的整数列转换为可空整数列...
albumIds = dt.AsEnumerable().Select(row => row.Field<int?>("F1"))
.Where(val => val.HasValue)
.Select(val => val.Value)
.Distinct()
.ToArray();
回答by sestocker
You just need to filter the null values out first. Then your LINQ expression should work great.
您只需要先过滤掉空值。那么您的 LINQ 表达式应该可以很好地工作。
回答by Jeremy
You need to check the fields for DBNull before you attempt the conversion using the Where method is probably easiest.
在尝试使用 Where 方法进行转换之前,您需要检查 DBNull 的字段可能是最简单的。
dt.AsEnumerable().Where(p => p.Field("F1") != DBNull.Value).Select(p => (int)p.Field("F1")).Distinct().ToArray();
回答by Sergey
I'll answer my own question.
我会回答我自己的问题。
Instead of using Linq I do a foreach loop and delete rows if value is null. and then do Linq distinct
我没有使用 Linq,而是执行 foreach 循环并在值为 null 时删除行。然后做 Linq distinct
foreach(DataRow row in dt.Rows)
{
if (String.IsNullOrEmpty(row["F1"].ToString()))
row.Delete();
}
dt.AcceptChanges();
albumIds = dt.AsEnumerable().Select(p => (int)p.Field<double>("F1")).Distinct().ToArray();
回答by Noah
Can you try this:
你能试试这个吗:
dt.AsEnumerable().Where(p => p.IsNull("F1") == false)
.Select(p => p.Field<int>("F1")).Distinct().ToArray();
I can't really check this as I don't have this DB setup
我真的无法检查这个,因为我没有这个数据库设置