How to check datatable column value is null or empty in c# linq

How to Check Datatable Column Value is Null or Empty in C# LINQ

In C#, you can use LINQ to check if a datatable column value is null or empty. Here’s an example:

    
      using System;
      using System.Data;
      using System.Linq;
      
      class Program
      {
          static void Main(string[] args)
          {
              DataTable dt = new DataTable();
              dt.Columns.Add("Name", typeof(string));
              dt.Columns.Add("Age", typeof(int));
              
              dt.Rows.Add("John Doe", 30);
              dt.Rows.Add("Jane Smith", DBNull.Value);
              dt.Rows.Add("Mark Johnson", null);
              
              var nullOrEmptyRows = dt.AsEnumerable().Where(row => string.IsNullOrEmpty(row.Field<string>("Name")) || row.Field<string>("Name") == string.Empty);
              
              foreach (var row in nullOrEmptyRows)
              {
                  Console.WriteLine(row.Field<string>("Name") + " is null or empty.");
              }
          }
      }
    
  

In this example, we first create a DataTable and add two columns – “Name” and “Age”. We then add three rows to the datatable. The second row has a null value for the “Name” column, and the third row has a DBNull value for the “Name” column.

We use LINQ’s Where method combined with a lambda expression to filter the rows where the “Name” column is null or empty. The lambda expression checks if the column value is null or an empty string using the string.IsNullOrEmpty() method.

In the foreach loop, we iterate over the filtered rows and print out the names of the rows that have null or empty “Name” values.

Leave a comment