Find and Delete empty records from Data Table using LINQ in C#, Asp.Net

 

When we are binding any data source with data table we may have empty records in data table. So, deleting empty records from data table is critical task in business point of view.

We can easily delete the empty records from data table by using LINQ in C#. First we have to identify the empty records from the data table as shown below.

Employees.Xml

<?xmlversion="1.0"encoding="utf-8" ?>

<Employees>

  <Employee>

    <Id>1</Id>

    <Name>A</Name>

  </Employee>

  <Employee>

    <Id>2</Id>

    <Name>B</Name>

  </Employee>

  <Employee>

    <Id></Id>

    <Name>C</Name>

  </Employee>

  <Employee>

    <Id></Id>

    <Name>D</Name>

  </Employee>

</Employees>

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="LINQDeleteEmptyRecords._Default" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>Delete empty records from Datatable</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:GridView ID="gv1" runat="server"></asp:GridView>

    </div>

    </form>

</body>

</html>

 

Default.aspx.cs

using System;

using System.Collections;

using System.Collections.Generic;

using System.Data;

using System.Linq;

 

namespace LINQDeleteEmptyRecords

{

    public partial class _Default : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            DataSet ds1 = new DataSet();

            ds1.ReadXml(Server.MapPath("Employees.xml"));

 

            DataTable dt1 = ds1.Tables[0];

            //ILIST<DataRow> RowsToDelete;

 

            //get empty records from data table

            RowsToDelete = dt1.AsEnumerable().Where(row => String.IsNullOrEmpty(row.Field<string>("Id"))).ToList().ForEach(row => row.Delete());

 

            //foreach(DataRow dr in RowsToDelete)

            //   dt1.Rows.Remove(dr);

 

            gv1.DataSource = dt1;

            gv1.DataBind();

        }

    }

}

 

By using dt1.AsEnumerable().Where(row => String.IsNullOrEmpty(row.Field<string>("Id"))).ToList(); code, we are identifying the empty records which have empty value for column Id and by using Remove() method we removed the record which are empty value for column Id or We can remove the rows directly by using LINQ Delete() method as shown above.

                                                                                                                                   LINQDeleteEmptyRecords.zip (20.21 kb)