How to check IS NULL on DataTable?

31,922

Solution 1

Use the strongly typed DataRow extension method Field which also supports nullable types:

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.

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.

foreach(DataRow row in rows)
{
    // ...
}

Solution 2

var rowsWithoutParent = dt.AsEnumerable().Where(r => r["ParentId"] == null);

var rowsWithParent = dt.AsEnumerable().Where(r => r["ParentId"] != null);

Solution 3

var rows = ds.Tables[0].AsEnumerable()
    .Where(r => r.IsNull("ParentId"));
Share:
31,922
Mogli
Author by

Mogli

Just started my career as a .Net developer. My quotes: Life is like encrypted .Config file, Nobody can understand. Error: Unable to sleep, Mind is still working. O God, Please get me out of this infinite For loop of mistakes :) True Love has no If condition and Return statement. &lt;3 First love is like Final variable, initialized only once and can not be modified further. My Life is full of goto: statements, no sequential flow, totally unstructured.*

Updated on February 02, 2020

Comments

  • Mogli
    Mogli over 4 years

    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.

       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.