如何在 DataTable.Select(Expression) 中使用 SELECT GROUP BY? [英] How do I use SELECT GROUP BY in DataTable.Select(Expression)?

查看:40
本文介绍了如何在 DataTable.Select(Expression) 中使用 SELECT GROUP BY?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试通过从每个组中选择第一行来删除重复的行.例如

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        C        C
4        C        C

我想要退货:

PK     Col1     Col2
1        A        B
3        C        C

我尝试了以下代码,但没有用:

I tried following code but it didn't work:

DataTable dt = GetSampleDataTable(); //Get the table above.
dt = dt.Select("SELECT MIN(PK), Col1, Col2 GROUP BY Col1, Col2);

推荐答案

DataTableSelect 方法只支持简单的过滤表达式,如 {field} = {值}.它不支持复杂的表达式,更不用说 SQL/Linq 语句了.

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

但是,您可以使用 Linq 扩展方法来提取 DataRow 的集合,然后创建一个 new DataTable.

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

这篇关于如何在 DataTable.Select(Expression) 中使用 SELECT GROUP BY?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆