Asif Asif - 8 days ago 6
C# Question

How to group DataTable results using Linq query expression

I have the following DataTable

DataTable BookTable = new DataTable();
//Add columns in Book Table
BookTable.Columns.Add("BookCategory", typeof(string));
BookTable.Columns.Add("BookName", typeof(string));
//Add rows in Book Table
BookTable.Rows.Add( "Programming", "C# basics");
BookTable.Rows.Add("Programming", "Java basics");
BookTable.Rows.Add("Networking", "Networking Basics");
BookTable.Rows.Add("Database", "Intro to Database");


I want to filter out Book Names on the basis of Book Category Column for this i have written the following Lambda expression

var BooksList = from Book in BookTable.AsEnumerable()
group Book by Book.Field<string>("BookCategory") into g
let list = g.ToList()
select new
{
BookCategory = g.Key,

BookNames = list.Select(x => x.Field<string>("BookName").ToString()) };


Now I have to print the out put in the following format;


  1. Programming


    • C# basics

    • Java basics


  2. Networking


    • Networking Basics


  3. Database


    • Intro to Database




I am interested in knowing how can i obtain the Book Names from book Categories in the following code;

foreach(var Book in BooksList)
{
Console.WriteLine(Book.BookCategory);
//logic to Obtain Book Names Here ;
}

Answer

You need insert String.Join in your code:

var BooksList = from Book in BookTable.AsEnumerable()
                        group Book by Book.Field<string>("BookCategory") into g
                        let list = g.ToList()
                        select new
                        {
                            BookCategory = g.Key,

                            BookNames = string.Join(" ; ",list.Select(x => x.Field<string>("BookName").ToString()))
                        };