Grouping datatable column using LINQ in C#

By Vijai Anand Oct 19, 2012
In this blog you will see how to perform group by in datatable using LINQ in C#


I have created a datatable which has the following columns and rows as shown in Figure

dt.png


I want to perform Group By based on Place column in MyTable and I need to get the Name column values for the grouped value which should look as shown in Figure

dtT.png

 

  Code Snippet:

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data;

 

namespace VijaiTesting

{

    class Program

    {

        static void Main(string[] args)

        {

            DataTable dt = new DataTable("MyTable");

            dt.Columns.Add(new DataColumn("Name"));

            dt.Columns.Add(new DataColumn("Place"));

            DataRow dr = dt.NewRow();

            dr["Name"] = "Vijai";

            dr["Place"] = "Chennai";

            dt.Rows.Add(dr);

            DataRow dr1 = dt.NewRow();

            dr1["Name"] = "Sujai";

            dr1["Place"] = "Chennai";

            dt.Rows.Add(dr1);

            DataRow dr2 = dt.NewRow();

            dr2["Name"] = "Ajai";

            dr2["Place"] = "Bangalore";

            dt.Rows.Add(dr2);

 

            var grouped = from table in dt.AsEnumerable()

                          group table by new { placeCol = table["Place"] } into groupby

                          select new

                          {

                              Value = groupby.Key,

                              ColumnValues = groupby

                          };

 

            foreach (var key in grouped)

            {               

                Console.WriteLine(key.Value.placeCol);

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

                foreach (var columnValue in key.ColumnValues)

                {

                    Console.WriteLine(columnValue["Name"].ToString());                   

                }

                Console.WriteLine();

            }

            Console.ReadLine();

        }

    }

}


Output:

outdt.png

Vijai Anand

Vijai Anand has been working in IT industry for over 5 years. He holds Bachelor's degree in Electronics and Communication Engineering. Vijai write articles and blogs related to SharePoint 2013, SharePoint 2010, Silv... Read more

COMMENT USING

PREMIUM SPONSORS

Hire Mobile & Web Developer on demand. 100% satisfaction. Try for 1 week or Money Back. Local and remote developers available all over USA.

Latest Blogs