LINQ CopyToDataTable问题

时间:2013-11-01 15:29:13

标签: c# linq linq-to-dataset

var results = gridViewDataTable.AsEnumerable()
                    .GroupBy(d => d.Field<string>("String1"))
                    .Select(g => g.OrderByDescending(d => d.Field<string>("String2")).CopyToDataTable();

我试图从这个LINQ查询中获取一个DataTable,但它给了我一个错误

) expected

谁能明白为什么?

3 个答案:

答案 0 :(得分:3)

你想念这个家伙:

var results = gridViewDataTable.AsEnumerable()
                    .GroupBy(d => d.Field<string>("String1"))
                    .Select(g => g.OrderByDescending(d => d.Field<string>("String2"))>>>>>>>)<<<<.CopyToDataTable();

答案 1 :(得分:1)

这将创建表格列表:

gridViewDataTable.AsEnumerable()
    .GroupBy(r => r.Field<string>("String1"))
    .Select(g => g.OrderByDescending(r => r.Field<string>("String2"))
                  .CopyToDataTable()); // bracket is missing here

这将创建具有分组和有序行的单个数据表(您还需要在此处使用SelectMany):

gridViewDataTable.AsEnumerable()
    .GroupBy(r => r.Field<string>("String1"))
    .SelectMany(g => g.OrderByDescending(r => r.Field<string>("String2"))) //here
    .CopyToDataTable();

答案 2 :(得分:1)

我打算编辑你的帖子以使其更具可读性,但后来我通过编辑意识到我有点让问题更明显。每个左括号都需要一个结束的括号,所以如果你刚开始分解不同的部分,那就很清楚了:

// Please don't actually format your code this way...
var results = gridViewDataTable.AsEnumerable()
                  .GroupBy(
                      d => d.Field<string>("String1")
                  )
                  .Select(
                      g => g.OrderByDescending (
                          d => d.Field<string>("String2")
                        )
                  ) // Needed to close out the Select()
                  .CopyToDataTable();

// How I would actually format this (makes it a little easier to
// break down a single line):
gridViewDataTable.AsEnumerable()
                 .GroupBy(d => d.Field<string>("String1"))
                 .Select(g => g.OrderByDescending(d => d.Field<string>("String2")))
                 .CopyToDataTable();