12

在我的项目中有两个数据表dtFaildtFaileddtFailed只有列名声明)。dtFail具有重复的“EmployeeName”列值。所以我采取了一个数据视图dvFail并完成了使它们不同的过程,如下面的代码所示:

失败

在此处输入图像描述

我尝试了以下代码:

   DataView dvFail = new DataView(dtFail);
   dtFail = dvFail.ToTable(true, "EmployeeName"); //showing only one column in dtFail

dtFailed只有一列

在此处输入图像描述

如果我喜欢下面

   DataView dvFail = new DataView(dtFail);
   dtFail = dvFail.ToTable(true, "EmployeeName","EmployeeRole","Status");

dtFailed显示但有重复的行

在此处输入图像描述

然后数据表dtFailed也存储重复的“EmployeeName”。

请帮助
提前致谢。

4

3 回答 3

7

试试这个查询 -

DataTable distinctTable = originalTable.DefaultView.ToTable( /*distinct*/ true);

有关更多信息,请点击以下链接 -

https://social.msdn.microsoft.com/Forums/en-US/ed9c6a6a-a93e-4bf5-a892-d8471b84aa3b/distinct-in-datatable-or-dataview?forum=adodotnetdataset

我希望这会对你有所帮助。

于 2015-06-29T11:01:47.150 回答
1

解决方案 1:

根据我理解的问题,我们需要考虑基于 EmployeeName 的重复项,我们不必担心其他列。如果是这种情况,下面的解决方案效果更好。

foreach(DataRow r in dtFail.AsEnumerable())
  {
   if (!dt1.AsEnumerable().Any(r1 => r1["EmployeeName"] == r["EmployeeName"]))
      {
     // if you don't want to copy entire row create new DataRow 
     // with required fields and add that row.
      dt1.Rows.Add(r.ItemArray);
      }
  }

如果您愿意,可以将 dt1 放回 dtFail。

解决方案 2:

如果我们需要考虑不同的行,我更喜欢下面的解决方案。

var temp = dtFail.AsEnumerable().Distinct();
dtFail = temp.CopyToDataTable();
于 2015-07-03T14:22:09.487 回答
0

I'm not sure it will be helpful or not. As far as I get from your question that you want EmployeeName to be distinct irrelevant to other columns. But if you do ToTable and turn on the distinct flag it will give all the distinct rows, doesn't matter how many columns are involved there. So if you mention only EmployeeName it will obviously give you distinct EmployeeNames, not all the columns associated with it.

So, thats what I did, initially select only the distinct EmployeeName columns and put it into a temp DataTable dtt.

DataTable dtt = dvFail.DefaultView.ToTable(true, "EmployeeName");

Secondly I've created another temp DataTable where we put the segregated rows from the main DataTable dtFail and set the column names manually.

DataTable TempDataTable = new DataTable();
DataTable dtFailed = new DataTable();

Prepare the columns in the dtFailed DataTable.

     if (dtFailed.Columns.Count == 0)
     {
           dtFailed.Columns.Add("EmployeeName");
           dtFailed.Columns.Add("EmployeeRole");
           dtFailed.Columns.Add("Status");
           dtFailed.Columns.Add("Date");
     }

Loop through the distinct EmployeeName dtt DataTable and match the EmployeeName and keep that selected first row in the TempDataTable. Finally all rows transferred into the dtFailed.

     for (int j = 0; j < dtt.Rows.Count; j++)
     {
           string EmployeeName = dtt.Rows[j]["EmployeeName"].ToString();
           TempDataTable = dvFail.Select("EmployeeName = " + EmployeeName).CopyToDataTable();
           dtFailed.Rows.Add(TempDataTable.Rows[0].ItemArray);
     }
于 2015-06-30T04:33:36.133 回答