0

谁能告诉,如何获得 LINQ 查询的结果包含 group by to DataTable 。

var query= from d in dtable.AsEnumerable()
           group d by d["Id"];

WId FirstName LastName Age
1   Jass      we       23 
1   Mady      wer      54
3   Servy     gr       22
4   Jan       fr       11

Expected
    WId FirstName LastName Age
    1   Jass      we       23 
    3   Servy     gr       22
    4   Jan       fr       11

谢谢普拉迪普

4

1 回答 1

1

如果您只想按 ID-Group 取第一人:

var distinctIdPersons = from p in dtable.AsEnumerable()
                        group p by p.Field<int>("WId") into IdGroups
                        select IdGroups.First();

或在方法语法中:

distinctIdPersons = dtable.AsEnumerable().GroupBy(r => r.Field<int>("WId"))
                                         .Select( g => g.First());

如果您想查看结果(用于测试目的),您可以使用string.Join

var output = string.Join(", ", distinctIdPersons.Select(r => 
    r.Field<string>("FirstName") + " " + r.Field<string>("LastName")));
Console.WriteLine(output); // Jass we, Servy gr, Jan fr
于 2012-07-03T20:20:59.317 回答