c#如何在包含许多数据表的数据集中查找重复记录?

时间:2020-01-21 18:09:29

标签: c# datatable duplicates dataset

我有一个包含许多DataTables的DataSet(至少一个表,可能更多)。有没有一种简单的方法来检查整个DataSet中是否有重复的记录? 重复的意思是: 每个表代表一个Student对象,并具有三列:StudentId,StudentName和NumberId(在此项目中,Students可以属于Numbers)。我需要一种方法来查看同一学生是否存在于两个或多个表中,也就是说,同一学生ID是否出现在任何表的多行中?
我已经尝试过-

protected void CheckForDuplicateStudents()
{
DataSet setStudents = new DataSet();
foreach (GridViewRow gvr in grdNumbers.Rows)//grdNumbers on html page
    {
        int numberId = int.Parse(grdNumbers.DataKeys[gvr.RowIndex].Value.ToString());

        //for each row in the grid, get the student enrollent as a dt
        //put each dt into the dset
        DataTable tblRoster = PerformanceAccess.GetStudentsInNumber(numberId);

        setStudents.Tables.Add(tblRoster);
    } 

var duplicatedRowsExist = dsetStudents.Tables[0].AsEnumerable()
                           .GroupBy(r => r, DataRowComparer.Default)
                           .Any(g => g.Count() > 1);`

//do stuff here if query returns any duplicate records
}

但是据我了解,此LINQ查询(和类似查询)仅在单个数据表中检查内的重复值,而不检查集合中的所有表。

有直接的方法可以做到吗?

编辑-我要澄清一下,每个表将有多行,其中每一行代表一个学生

`

2 个答案:

答案 0 :(得分:0)

您的问题有些细节,但是如果我们按照一组假设进行工作:

  • 您有一个包含N个表的数据集
  • 所有表的int类型的StudentID列
  • 您要检测已重复的特定整数

以下代码将为您提供一个引用所有重复行的列表:

HashBag<int> idx = new HashBag<int>();
List<DataRow> dupRows = new List<DataRow>();

foreach(DataTable dt in dataset.Tables)
{
  foreach(DataRow dr in dt.Rows)
  {
    int sid = (int)dr["StudentID"];
    if(idx.Contains(sid))
      dupRows.Add(dr);
    else
      idx.Add(sid);
  }
}

DataRows具有指向其所在表的链接,因此,如果您需要引用特定行所居住的数据表,请致电例如dupRows[0].Table

如果要第一行及其所有重复项,请考虑使用字典:

Dictionary<int, DataRow> idx = new Dictionary<int, DataRow>();
List<DataRow> dupRows = new List<DataRow>();

foreach(DataTable dt in dataset.Tables)
{
  foreach(DataRow dr in dt.Rows)
  {
    int sid = (int)dr["StudentID"];
    if(idx.Contains(sid))
      dupRows.Add(dr);
    else
      idx[sid] = dr;
  }
}

现在字典包含遇到的第一行,并且列表包含它的所有重复项

答案 1 :(得分:0)

您可以使用(不同方法)

var duplicatedRowsExist = dsetStudents.Tables[0].AsEnumerable().GroupBy(r => r, DataRowComparer.Default).Any(g => g.Count() > 1).distinct()