我有一个有几千行的数据表,有三列,我想搜索数据表中的一个特定列来查找Distinct值。我试过这个:
DataRow[] dr = datatable.Select("SELECT DISTINCT Amount ");
Amount是我尝试按值分组的列名。
我得到的错误是: 语法错误:'DISTINCT'运算符
后缺少操作数由于
答案 0 :(得分:4)
DataView view = new DataView(datatable);
DataTable distinctAmount = view.ToTable(true, "Amount", "xxx","xxxx"...);
答案 1 :(得分:2)
如果您想要不同的值,可以尝试使用DataView.ToTable()
方法:
var distinct = datatable.DefaultView.ToTable(true, new[] { "Amount" });
foreach (DataRow item in distinct.Rows)
{
Console.WriteLine(item[0]);
}
只需将示例方法添加到Amount
分组,并根据此分组显示行(假设数据表中还有另一个OtherColumn
列):
datatable.Rows
.Cast<DataRow>()
.GroupBy(r => r["Amount"])
.ToList().ForEach(group =>
{
Console.WriteLine("Group {0} has the following elements", group.Key);
group.ToList().ForEach(row =>
{
Console.WriteLine(row["OtherColumn"]);
});
});