2012-06-30 93 views
0

我有一個arraylist包含來自不同數據庫的值,但它存儲一些重複的值,所以我想刪除重複的值並在ARRay列表中只存儲唯一的值。如何從ARRAYLIST刪除重複的值

那麼,這怎麼可能實現呢?

在此先感謝... Mitesh

+1

你是如何在ArrayList中添加值的工作? –

+0

您使用的是哪個版本的.NET框架? –

+0

可能的重複[在C#中刪除列表](http://stackoverflow.com/questions/47752/remove-duplicates-from-a-listt-in-c-sharp) – adatapost

回答

4

您可以用HashSet取代你的ArrayList。從文檔:

The HashSet<T> class provides high performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order. 

如果它是絕對必要使用ArrayList,你可以使用一些LINQ到與Distinct命令刪除重複。

var distinctItems = arrayList.Distinct() 
0

如果必須使用ArrayList,使用排序方法。 這是一個很好的鏈接@Sort Method of ArrayList。 對列表進行排序後,使用算法迭代/比較所有元素並刪除重複項。

玩得開心,

湯米Kwee

+0

我不想排序,但想刪除重複。 –

+0

@Mitesh,列表排序後,您可以通過迭代所有元素來刪除重複項。 –

+0

Distinct方法自身刪除重複項。如果您要使用linq方法,請使用正確的方法。 – Falanwe

2

如果可以的話,你應該使用HashSet,或任何其他集合類。這種操作更有效率。 HashSet的主要默認值是元素的排序不保證與原始列表保持一致(根據您的規範,這可能會也可能不是問題)。否則,如果您需要保留排序,但只需在列舉值時列出刪除的副本,則可以使用linq的Distinct方法。請小心,不要運行此查詢,並在每次修改陣列列表時複製結果,因爲它可能會影響您的表演。

11

讓我們嘗試另一種方法。相反,刪除重複,避免添加任何重複。這可能會在您的環境中更有效率。 下面是一個示例代碼:

ArrayList<String> myList = new ArrayList<string>(); 
foreach (string aString in myList) 
{ 
    if (!myList.Contains(aString)) 
    { 
     myList.Add(aString); 
    } 
} 
1
 Hashtable ht = new Hashtable(); 
     foreach (string item in originalArray){ 
      //set a key in the hashtable for our arraylist value - leaving the hashtable value empty 
      ht[item] = null; 
     } 

    //now grab the keys from that hashtable into another arraylist 
    ArrayList distincArray = new ArrayList(ht.Keys); 
+1

在上面的代碼添加行之前:Hashtable ht = new Hashtable(); – sanjay

3

您可以使用此代碼時有一個ArrayList

ArrayList arrayList; 
//Add some Members :) 
arrayList.Add("ali"); 
arrayList.Add("hadi"); 
arrayList.Add("ali"); 

//Remove duplicates from array 
    for (int i = 0; i < arrayList.Count; i++) 
    { 
     for (int j = i + 1; j < arrayList.Count ; j++) 
      if (arrayList[i].ToString() == arrayList[j].ToString()) 
       arrayList.Remove(arrayList[j]); 
    } 
+1

非常優雅感謝。我有一個問題,重複的最後一個元素沒有刪除,但我解決了循環2次。 – Nicola

+0

您可以編輯答案並提交給其他成員;坦克很多 –