Вопрос

I have a DataTable that gets me ID, Description, OptionID

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

Then based on a criteria I select OptionID 1 and add to list in order to remove duplicates:

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

Here is How I remove duplicates and and return a list of 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;
    }

And then assign the returned list of DataRow to Repeater, now I want to sort this list, tried using lst.sort() but I get an exception of Failed to compare two elements in the array. Any help would be appreciated.

PS. Am using .NET 2.0

Это было полезно?

Решение

You have to say sort how to sort. Take a look at this example

You have to do some kind of this

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

lst.Sort(MyComp)

Другие советы

Remove Duplicates

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

Here Links below

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

For remove duplicates in column

http://dotnetguts.blogspot.com/2007/02/removing-duplicate-records-from.html
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top