我想在我的DataTable中应用以下Sql查询
SELECT MakeDistinct AS AfterDistinct
, COUNT(MakeDistinct) AS Count
FROM MyTable
GROUP BY MakeDistinct
有关详细信息,请参阅此Question
答案 0 :(得分:3)
类似的东西:
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
然后聚合DataTable
更有效。
答案 1 :(得分:0)
您正在寻找DataTable.Compute
。该方法可以为您计算聚合函数。所以你会得到类似的东西:
object sumObject;
sumObject = myDataTable.Compute("Sum(Count)", ""); // second parameter is the where clause
要按列进行分组,请参阅此问题:Efficient DataTable Group By。它提供了Linq实现以及“非Linq”实现。
答案 2 :(得分:0)
使用 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()
};