如何使用Linq查询表达式对DataTable结果进行分组

时间:2016-11-28 11:09:22

标签: c# linq lambda

我有以下DataTable

Array
(
    [0] => https://instagram.fskg1-1.fna.fbcdn.net/t51.2885-15/s320x320/e35/c180.0.720.720/15057412_1332184313482140_6642273356848562176_n.jpg?ig_cache_key=MTM5MDE1NzI5MDIyOTAwMjYwMQ%3D%3D.2.c
)

我想根据图书分类栏过滤图书名称,因为我写了以下Lambda表达式

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");

现在我必须以下列格式打印输出;

  1. 编程
    • C#basics
    • Java基础知识
  2. 网络
    • 网络基础
  3. 数据库
    • 数据库简介
  4. 我有兴趣知道如何从以下代码中的图书类别中获取图书名称;

    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())                  };
    

1 个答案:

答案 0 :(得分:0)

您需要在代码中插入String.Join:

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()))
                        };