ToTable()不返回不同的记录?

时间:2013-07-02 11:56:42

标签: c# .net ado.net

我正在使用数据表来返回不同的记录但不知何故它不会给我返回不同的记录 我试过像

dt.DefaultView.ToTable(true, "Id");
foreach (DataRow row in dt.Rows)
            {
                System.Diagnostics.Debug.Write(row["Id"]);

            }

它仍然会返回所有记录。这可能有什么问题?

更新

我的sql如下

   select  t.Update ,t.id as Id, t.name ,t.toDate,t.Age from  tableA  t  Where t.Id = 55 
   union
   select  t.Update ,t.id as Id, t.name ,t.toDate,t.Age  from tableB t  Where t.Id = 55
   order by Id

我的查询非常难以区分,因为这里提到了很多列。

4 个答案:

答案 0 :(得分:5)

如果使用数据库,最好使用sql仅返回不同的记录(例如,使用DISTINCTGROUP BY或窗口函数)。

如果要在内存中过滤表格,也可以使用Linq-To-DataSet

dt = dt.AsEnumerable()
    .GroupBy(r=>r.Field<int>("Id")) // assuming that the type is `int`
    .Select(g=>g.First())           // take the first row of each group arbitrarily 
    .CopyToData‌​Table();

请注意,当您想要过滤这些行或者您不想任意取每个id-group的第一行时,Linq的强大功能会启动,例如最后一行(根据{{1} } field。也许你也想订购这些团体或者只返回前十名。没问题,只需使用DateTimeOrderBy

答案 1 :(得分:2)

问题在于你没有抓住新桌子:

var newDt = dt.DefaultView.ToTable(true, "Id");
foreach (DataRow dr in newDt.Rows) ...

ToTable方法不会修改现有表 - 它会创建一个新表。

答案 2 :(得分:1)

DataView view = new DataView(table);
DataTable distinctValues = view.ToTable(true, "Id");

答案 3 :(得分:0)

您没有将返回值分配给任何变量,请尝试此

DataTable dtnew = dt.DefaultView.ToTable(true, "Id");

foreach (DataRow row in dtnew.Rows)
{
    System.Diagnostics.Debug.Write(row["Id"]);
}