【问题标题】:Remove duplicate rows from DataTable with condition - C#使用条件从 DataTable 中删除重复行 - C#
【发布时间】:2020-06-19 06:34:46
【问题描述】:

我有一个如下的数据表

StudentID  Marks 
 AAA        NULL
 AAA        100
 BBB        200

我必须通过在以下条件下检查 studentID 从数据表中删除该行

  1. 如果有相同的学生 ID,则删除具有 NULL 值的行并仅显示具有值的学生 ID。
  2. 如果该学生的两个分数均为 NULL,则仅显示一行。

结果数据表应该是

StudentID  Marks 
 AAA        100
 BBB        200

我尝试使用下面的函数从上表中删除重复的行

     public DataTable RemoveDuplicateRows(DataTable dTable, string colName)
    {
        Hashtable hTable = new Hashtable();
        ArrayList duplicateList = new ArrayList();

        //Add list of all the unique item value to hashtable, which stores combination of key, value pair.
        //And add duplicate item value in arraylist.
        foreach (DataRow drow in dTable.Rows)
        {
            if (hTable.Contains(drow[colName])&& drow["Marks"]==null)
            {
                duplicateList.Add(drow);
            }
            else
            {
                hTable.Add(drow[colName], string.Empty);
            }
        }

        //Removing a list of duplicate items from datatable.
        foreach (DataRow dRow in duplicateList)
            dTable.Rows.Remove(dRow);

        //Datatable which contains unique records will be return as output.
        return dTable;
    }

【问题讨论】:

  • 还要注意datatabledatatables标签的区别。第二个在这个问题中没有位置
  • 第 3 点毫无意义。这纯粹是随意的吗?
  • 为什么不创建一个对象列表并使用 linq 来匹配您的条件,然后从中创建一个数据表,而不是使用 foreach 循环?
  • 您的代码不会根据您的条件尝试删除。它删除第二个和后续条目,留下第一个,不管应该保留哪一个。
  • @JonathanWillcock Point 2 作为我的代码工作。

标签: c# asp.net datatable


【解决方案1】:
DataTable datatabble = new DataTable();
datatabble.Columns.Add("studentid", typeof(string));
datatabble.Columns.Add("marks", typeof(int));

datatabble.Rows.Add("AAA");
datatabble.Rows.Add("AAA",100);
datatabble.Rows.Add("BBB",200);

var duplicates = datatabble.AsEnumerable().GroupBy(r => r[0]).Where(gr => gr.Count() > 1)
            .Select(dupl => dupl.Key).ToList();

var result = datatabble.AsEnumerable().Where(x => 
        (
           (duplicates.Contains(x[0]) && !string.IsNullOrEmpty(x[1].ToString()))
           || !duplicates.Contains(x[0])
        )           
        ).ToList();

输出:您可以看到带有过滤空值的 2 行计数的输出。

【讨论】:

    猜你喜欢
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    • 2023-01-22
    • 1970-01-01
    相关资源
    最近更新 更多