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

Jam*_*mes 0 .net c# ado.net

我正在使用数据表返回我不同的记录,但是以某种方式它没有返回我尝试过的不同记录

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

            }
Run Code Online (Sandbox Code Playgroud)

它仍然返回我所有的记录。这有什么问题吗?

更新

我的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
Run Code Online (Sandbox Code Playgroud)

在我的查询中很难做到与众不同,因为有许多列比这里提到的多。

Tim*_*ter 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();
Run Code Online (Sandbox Code Playgroud)

请注意,当您要过滤这些行或不想随意获取每个id-group的第一行,而是例如最后一行(根据DateTime字段)时,Linq的功能就开始了。也许您还想订购组或只返回前十组。没问题,只需使用OrderBy和即可Take