3

考虑我的数据表,

Id  Name  MobNo
1   ac    9566643707
2   bc    9944556612
3   cc    9566643707

如何在不使用 LINQ 的情况下删除 c#3中包含重复MobNo列值的行。我在 SO 上看到过类似的问题,但所有答案都使用 LINQ。

4

5 回答 5

4

以下方法做了我想要的....

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]))
                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;
    }
于 2010-05-24T06:49:10.117 回答
1

当您阅读 CSV 文件时(一些伪代码,但您得到了图片):

List<String> uniqueMobiles = new List<String>();

String[] fileLines = readYourFile();

for (String line in fileLines) {
   DataRow row = parseLine(line);
   if (uniqueMobiles.Contains(row["MobNum"])
   {
       continue;
   }
   uniqueMobiles.Add(row["MobNum"]);
   yourDataTable.Rows.Add(row);       
}

这只会将具有唯一手机的记录加载到您的数据表中。

于 2010-05-24T06:26:07.723 回答
1

这是最简单的方法。

**

var uniqueContacts = dt.AsEnumerable()
                       .GroupBy(x=>x.Field<string>("Email"))
                       .Select(g=>g.First());

** 我在这个线程 LINQ 中发现它可以根据特定行的值从数据表中删除重复的行

我将它作为数据表返回对我来说实际上是什么

DataTable uniqueContacts = dt.AsEnumerable()
                           .GroupBy(x=>x.Field<string>("Email"))
                           .Select(g=>g.First()).CopyToDataTable();
于 2015-03-18T09:25:41.757 回答
0

您可能想先查看 DISTINCT 的内部工作原理,然后再在您的清晰数据库上运行它(一定要备份!),但如果它像我认为的那样工作(获取第一个值),您应该能够使用(东西非常类似于)以下SQL:

DELETE FROM YourTable WHERE Id NOT IN (SELECT DISTINCT Id, MobNo FROM YourTable);
于 2010-05-24T06:18:14.690 回答
0

您可以在 C# 中使用“IEqualityComparer”

于 2010-05-24T09:35:03.070 回答