【问题标题】:less expensive way to find duplicate rows in a datatable?在数据表中查找重复行的更便宜的方法?
【发布时间】:2013-04-24 18:25:32
【问题描述】:

我想查找 DataTable 中的所有行,其中每组列都是重复的。我目前的想法是获取多次出现的所有行的索引列表,如下所示:

public List<int> findDuplicates_New()
        {
            string[] duplicateCheckFields = { "Name", "City" };
            List<int> duplicates = new List<int>();
            List<string> rowStrs = new List<string>();
            string rowStr;

            //convert each datarow to a delimited string and add it to list rowStrs
            foreach (DataRow dr in submissionsList.Rows)
            {
                rowStr = string.Empty;
                foreach (DataColumn dc in submissionsList.Columns)
                {
                    //only use the duplicateCheckFields in the string   
                    if (duplicateCheckFields.Contains(dc.ColumnName))
                    {
                        rowStr += dr[dc].ToString() + "|";
                    }
                }
                rowStrs.Add(rowStr);
            }

            //count how many of each row string are in the list
            //add the string's index (which will match the row's index)
            //to the duplicates list if more than 1
            for (int c = 0; c < rowStrs.Count; c++)
            {
                if (rowStrs.Count(str => str == rowStrs[c]) > 1)
                {
                    duplicates.Add(c);
                }
            }
            return duplicates;
        }

但是,这不是很有效:遍历字符串列表并获取每个字符串的计数是 O(n^2)。我查看了this solution,但不知道如何将它用于超过 1 个字段。我正在寻找一种更便宜的方法来处理这个问题。

【问题讨论】:

标签: c# datatable


【解决方案1】:

试试这个:

How can I check for an exact match in a table where each row has 70+ columns?

本质是做一个集合来存储行的哈希值,并且只在具有冲突哈希值的行之间进行比较,复杂度将是 O(n)

...

如果您有 大量 行并且存储哈希本身是一个问题(这种情况不太可能发生,但仍然...),您可以使用Bloom filter。布隆过滤器的核心思想是计算several每一行的不同哈希值,并将它们用作位图中的地址。当您扫描行时,您可以仔细检查已经在位图中设置了所有位的行。

【讨论】:

  • 我同意您提出的解决方案是 O(n)。但是除非我读错了,否则看起来每个重复项的第一个实例不会被识别为重复项,因为它不会已经在哈希集中。对于任何给定的重复行集,我想将每一行标识为重复行。
  • 然后使用一个字典,其中键是您从所有列计算出的哈希值,值是行 ID,这样如果您发现键存在,则与它一起存储的 ID 标识重复
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-21
  • 2021-02-25
  • 2012-11-21
  • 1970-01-01
相关资源
最近更新 更多