代码之家  ›  专栏  ›  技术社区  ›  Freakishly

如何根据列的值完全删除数据表中的重复项?

  •  0
  • Freakishly  · 技术社区  · 15 年前

    数据表中有3列

    ID名称计数

    1詹姆斯4345

    2克里斯汀89231

    3詹姆斯599

    4苏尼尔317113

    我需要去掉第1行和第3行,新的数据表只返回第2行和第4行。我在建议中发现了一个很好的相关问题-- this guy . 但他的解决方案使用了哈希表,只删除了第3行,而不是第1行和第3行。救命!

    3 回复  |  直到 15 年前
        1
  •  0
  •   ACP    15 年前

    我试过这个 Remove duplicates from a datatable

    using System.Data;
    using System.Linq;
    ...
    //assuming 'ds' is your DataSet
    //and that ds has only one DataTable, therefore that table's index is '0'
    DataTable dt = ds.Tables[0];
    DataView dv = new DataView(dt);
    string cols = string.Empty;
    foreach (DataColumn col in dt.Columns)
    {
    if (!string.IsNullOrEmpty(cols)) cols += ",";
    cols += col.ColumnName;
    }
    dt = dv.ToTable(true, cols.Split(','));
    ds.Tables.RemoveAt(0);
    ds.Tables.Add(dt);
    

    遵循单行代码将避免重复的行。

    ds.Tables["Employee"].DefaultView.ToTable(true,"Name");
    

    数据集对象

    dt.DefaultView.ToTable( true, "Name");
    

    数据表对象

        2
  •  0
  •   Ryk    15 年前

    像这样的东西怎么样?

    伪代码: 假设对象有3个属性:【ID、名称、值】,并被称为NameObjects,并且是IEnumerable(列出NameObjects;)

    var _newNameObjectList = new List<NameObject>();
    
    foreach(var nameObject in NameObjecs)
    {
       if(_newNameObjectList.Select(x => x.Name == nameObject.Name).ToList().Count > 0)
       {
          _newNameObjectList.RemoveAll(x => x.Name == nameObject.Name);
          continue;
       }
       else
       {
          _newNameObjectList.Add(nameObject); 
       }
    }
    

    这应该有效。这将使用命名空间系统.linq;

        3
  •  0
  •   Freakishly    15 年前

    好吧,我看了一下潘迪娅给我的博客。在评论部分,一个叫KevinMorris的人用一本适合我的C字典发布了一个解决方案。

    在我的主块中,我写道:

    string keyColumn = "Website";
    RemoveDuplicates(table1, keyColumn);
    

    我的removeduplicates函数定义为:

        private void RemoveDuplicates(DataTable table1, string keyColumn)
    {
        Dictionary<string, string> uniquenessDict = new Dictionary<string, string>(table1.Rows.Count);
        StringBuilder sb = null;
        int rowIndex = 0;
        DataRow row;
        DataRowCollection rows = table1.Rows;
        while (rowIndex < rows.Count - 1)
        {
            row = rows[rowIndex];
            sb = new StringBuilder();
                sb.Append(((string)row[keyColumn]));
    
    
            if (uniquenessDict.ContainsKey(sb.ToString()))
            {
                rows.Remove(row);
                if (RemoveAllDupes)
                {
                    row = rows[rowIndex - 1];
                    rows.Remove(row);
                }
            }
            else
            {
                uniquenessDict.Add(sb.ToString(), string.Empty);
                rowIndex++;
            }
        }
    }
    

    如果你去 the blog 您将发现一个更通用的函数,它允许在多个列上嗅探重复数据。我已经添加了一个标志——removeAllDupes——以防我要删除所有重复的行,但这仍然假定行是按名称排序的,并且只涉及重复的行,而不涉及三次、四次等。如果有人可以,请更新此代码以反映对其的删除。