LINQ to perform operation with DataTable in C#

If you are a C#.Net developer, then you must be familiar with DataTable and LINQ.
In C#, a DataTable is an in-memory object to represent data in tabular format i.e. rows and columns.
Once you get data in a DataTable object there could be the various operation that can be performed.

In this blog, I will explain about the LINQ code that is very helpful while working with DataTable.
For eg - If you want to do a sum of a column data or want to check a null value in a cell.

Select N rows from DataTable using LINQ in C#


Suppose you have your data in a DataTable but you want to show or manipulate only 4 or 5 or 6 or n records, then below is the C# code to implement this facility.



              string spQuery = "GetData";
            SqlParameter[] param = new SqlParameter[1];
            param[0] = new SqlParameter("@department", txtDept.Text);
            DataSet ds = //Your Data Logic
            var topNRows = from EmpData in ds.Tables[0].AsEnumerable().Take(3)                               
                  select new
                   {
                  Name = EmpData.Field<string>("name"),
                  Dept = EmpData.Field<string>("dept"),
                  City = EmpData.Field<string>("city"),
                  Grade= EmpData.Field<string>("grade")
                   };

                rptData.DataSource = topRows;
                rptData.DataBind();
           



Below code is to sum the value of a column called 'marks' available in a DataTable.


decimal totalMarks = ds.Tables[0].AsEnumerable().Sum(r => r.Field<decimal?>("marks") ?? 0); 

Below code is to check the row count where the particular column should not contain a null value.


int valueCount = ds.Tables[0].AsEnumerable().Where(c=>c.Field<decimal?>("studentCode") != null).Count();


Find records from DataTable using LINQ in C#





int deptCount = dTable.AsEnumerable().Where(c => c.Field<string>("dept") == "IT").Count();


C# code to select value from DataTable


       


 DataRow[] result = dtable.Select("marks >= 75");

        foreach (DataRow row in result)

        {

            string stuname = row[0].ToString();

            string rollno = row[1].ToString();
        }


Comments

Popular

What's new in C# 6.0 language - All new features of C# 6.0 for developers

SharePoint Interview Questions and Answers