2013-08-02 164 views
0

的名單我有一個DataTable這讓我ID, Description, OptionID排序的DataRow

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

回答

1

你必須說如何排序。 看看這個example

你必須做某種這

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

lst.Sort(MyComp) 
-1

刪除重複

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