C# 如何在DataTable上检查IS NULL?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15523917/
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
How to check IS NULL on DataTable?
提问by Mogli
In my case i am passing a sql query and getting data in dataset, but problem occurs when i try to get the rows where ParentId column contain NULL.This is the piece of code.
在我的情况下,我正在传递一个 sql 查询并在数据集中获取数据,但是当我尝试获取 ParentId 列包含 NULL 的行时出现问题。这是一段代码。
DataSet ds = GetDataSet("Select ProductId,ProductName,ParentId from ProductTable");
//ds is not blank and it has 2 rows in which ParentId is NULL
DataRow[] Rows = ds.Tables[0].Select("ParentId IS NULL");
But still i am not getting any rows. Need help. Thanx.
但我仍然没有得到任何行。需要帮忙。谢谢。
采纳答案by Tim Schmelter
Use the strongly typed DataRow
extension method Field
which also supports nullable types:
使用也支持可为空类型的强类型DataRow
扩展方法Field
:
IEnumerable<DataRow> rows = ds.Tables[0].AsEnumerable()
.Where(r => !r.Field<int?>("ParentId").HasValue);
Note that i've used Enumerable.Where
which is a Linq extension method to filter the table.
请注意,我使用了Enumerable.Where
哪个 Linq 扩展方法来过滤表。
If you want an array use ToArray
, if you want a new DataTable
use CopyToDataTable
. If you simply want to enumerate the result use foreach
.
如果你想要一个数组使用ToArray
,如果你想要一个新的DataTable
使用CopyToDataTable
。如果您只想枚举结果,请使用foreach
.
foreach(DataRow row in rows)
{
// ...
}
回答by andy
Check
查看
ds.Tables.Count
then
然后
ds.Tables[0].Rows.Count
回答by Moondustt
You can access the items like this:
您可以像这样访问项目:
String value = ds.Tables[0].Rows[RowNum][ColNum].ToString();
回答by sll
var rowsWithoutParent = dt.AsEnumerable().Where(r => r["ParentId"] == null);
var rowsWithParent = dt.AsEnumerable().Where(r => r["ParentId"] != null);
回答by Rased Dot Net
var rows = ds.Tables[0].AsEnumerable()
.Where(r => r.IsNull("ParentId"));
回答by izik f
work for me:
为我工作:
DataTable newDt = dt.AsEnumerable().Where(r => r["column name"] == DBNull.Value).CopyToDataTable();
if equal to null
is not work because is return DBNull
如果等于null
无效,因为是返回DBNull