对DataRow列表进行排序

本文关键字:排序 列表 DataRow | 更新日期: 2023-09-27 18:25:52

我有一个DataTable,它可以让我获得ID, Description, OptionID

ID  Description OptionID
1   TEST        1
2   TEST2       1
2   TEST3       1
3   TEST4       2

然后根据一个标准,我选择OptionID 1并添加到列表中以删除重复项:

 DataRow[] datarow = dt.Select("OptionID = 1");
 AddToList(lst, datarow);

以下是我如何删除重复并返回DataRow:的列表

 private static List<DataRow> RemoveDuplicate(List<DataRow> drAllOptions)
    {
        List<DataRow> ldr = new List<DataRow>();
        List<int> safeGuard = new List<int>();
        foreach (DataRow dr in drAllOptions)
        {
            if (!safeGuard.Contains(Convert.ToInt32(dr["ID"])))
            {
                ldr.Add(dr);
                safeGuard.Add(Convert.ToInt32(dr["ID"]));
            }
        }
        return ldr;
    }

然后将返回的DataRow列表分配给Repeater,现在我想对这个列表进行排序,尝试使用lst.sort(),但我得到了Failed to compare two elements in the array.的异常。如有任何帮助,将不胜感激。

PS。我正在使用.NET 2.0

对DataRow列表进行排序

你必须说sort如何排序。看看这个例子

你必须做一些

private static int MyComp(DataRow left, DataRow right)
{
    if (left["ID"] == right["ID"])
    {
       return 0;
    } 
    else
    {
       return 1;
    }
}
lst.Sort(MyComp)

删除重复

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;
}

此处链接下方

http://www.dotnetspider.com/resources/4535-Remove-duplicate-records-from-table.aspx
http://www.dotnetspark.com/kb/94-remove-duplicate-rows-value-from-datatable.aspx

用于删除列中的重复项

http://dotnetguts.blogspot.com/2007/02/removing-duplicate-records-from.html