Grouping datatable column 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

Ebook Download
View all
Learn
View all