我想在我的 DataTable 中应用以下 Sql 查询
SELECT MakeDistinct AS AfterDistinct
, COUNT(MakeDistinct) AS Count
FROM MyTable
GROUP BY MakeDistinct
有关更多详细信息,请参阅此问题
就像是:
var query = from row in table.AsEnumerable()
group row by row.Field<int>("MakeDistinct") into grp
select new {AfterDistinct = grp.Key, Count = grp.Count()};
foreach(var row in query) {
Console.WriteLine("{0}: {1}", row.AfterDistinct, row.Count);
}
请注意,在数据库服务器上进行聚合通常比DataTable
通过网络填充 a 然后聚合DataTable
.
您正在部分寻找DataTable.Compute
. 该方法可以为您计算聚合函数。所以你会得到类似的东西:
object sumObject;
sumObject = myDataTable.Compute("Sum(Count)", ""); // second parameter is the where clause
有关按列分组,请参阅此问题:Efficient DataTable Group By。它提供了一个 Linq 实现以及一个“非 Linq”实现。
使用System.Data.DataSetExtensions并尝试这样的事情
var result = from row in dt.AsEnumerable()
group row by row.Field<int>("MakeDistinct") into grp
select new
{
MakeDistinct = grp.Key,
Count = grp.Count()
};