How do I use SELECT GROUP BY in DataTable.Select(Expression)?

后端 未结 4 1840
刺人心
刺人心 2020-12-01 09:42

I try to remove the duplicate rows by select a first row from every group. For Example

PK     Col1     Col2
1        A        B
2        A        B
3                 


        
4条回答
  •  再見小時候
    2020-12-01 10:00

    DataTable's Select method only supports simple filtering expressions like {field} = {value}. It does not support complex expressions, let alone SQL/Linq statements.

    You can, however, use Linq extension methods to extract a collection of DataRows then create a new DataTable.

    dt = dt.AsEnumerable()
           .GroupBy(r => new {Col1 = r["Col1"], Col2 = r["Col2"]})
           .Select(g => g.OrderBy(r => r["PK"]).First())
           .CopyToDataTable();
    

提交回复
热议问题