How to get all the datacolumn values from datatable using LINQ in C#


I have created a datatable named “Employees” which has the following columns and rows as shown in Figure.

dtEmployees.png


Here you will see how to get all the datacolumn values from Employees datatable using LINQ.

Code snippet:


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data;

 

namespace LINQinDatatable

{

    class Program

    {

        static void Main(string[] args)

        {

            //Create a datatable

            DataTable dtEmployees = new DataTable("Employees");

          

            //Create a datacolumn to store Employee name values

            DataColumn dcName = new DataColumn("Name");

            //Create a datacolumn to store Employee designation values

            DataColumn dcDesignation = new DataColumn("Designation");

            //Create a datacolumn to store Employee location values

            DataColumn dcLocation = new DataColumn("Location");

           

            //Add the datacolumns to the datatable          

            dtEmployees.Columns.Add(dcName);

            dtEmployees.Columns.Add(dcDesignation);

            dtEmployees.Columns.Add(dcLocation);

 

            //Create datarows

            DataRow drEmployee = dtEmployees.NewRow();         

            drEmployee[dcName] = "Vijai";

            drEmployee[dcDesignation] = "Associate";

            drEmployee[dcLocation] = "Bangalore";

 

            DataRow drEmployee1 = dtEmployees.NewRow();         

            drEmployee1[dcName] = "Anand";

            drEmployee1[dcDesignation] = "Associate";

            drEmployee1[dcLocation] = "Chennai";

 

            //Add the datarow to the datatable

            dtEmployees.Rows.Add(drEmployee);

            dtEmployees.Rows.Add(drEmployee1); 

         

            //LINQ to query all the values from the datatable

            IEnumerable < DataRow > query = from dt in dtEmployees.AsEnumerable()

                                     select dt;

 

            //Get all the values from datatble

            foreach (DataRow dr in query)

            {

                Console.WriteLine("----------------------------------");               

                Console.WriteLine(dr.Field<string>("Name"));

                Console.WriteLine(dr.Field<string>("Designation"));

                Console.WriteLine(dr.Field<string>("Location"));               

            }

            Console.ReadLine();

        }

    }

}

 


Output:

output.png