How to get a particular 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 only the Name 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 to get a particular datatcolumn values from datatable

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

                                     select dt.Field<string>("Name");

 

            //Get all the employee Names from datatble

            foreach (string employeeName in query)

            {

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

                Console.WriteLine(employeeName);             

            }

            Console.ReadLine();

        }

    }

}