2010-07-27 104 views
0

我必須檢查ArrayList中的重複記錄。在ArrayList中,每個項目在插入新項目之前至少應該有2次。每個示例如何在arrayList中查找重複項?

Example 1: 

AL(0) = '1' 
AL(1) = '1' 
AL(2) = '2' 
AL(3) = '2' 
AL(4) = '2' 
Method has to return = True, because each value has atleast 2 times in the list. 

Example 2: 

AL(0) = '1' 
AL(1) = '1' 
AL(2) = '2' 
AL(3) = '3' //Trying to insert new Item, But It should not 

Method has to return = 'false', because '2' has 1 time in the list. So I dont 
want insert '3' in ArrayList and return false. 
+1

數組是否總是排序?如果不是,在'[b,b,b,a,a]'上,你能插入另一個'b'嗎?當更好的結構存在時,爲什麼要使用數組列表(即通用列表,例如'List ')。最後,你有單個數組還是多個? – Kobi 2010-07-27 04:23:48

回答

1

如果你的ArrayList是有序的,並且包含數字的字符串(如在您的文章中所示),然後下面的功能應該工作:

Private Function OKToInsertSorted(ByVal theArrayList As ArrayList, _ 
            ByVal stringToInsert As String) As Boolean 

    With theArrayList 
     If CInt(stringToInsert) < CInt(.Item(.Count - 1)) Then Return False 
     If .Count <= 1 Then 
      If stringToInsert = "1" Then Return True Else Return False 
     End If 
     If .Item(.Count - 1).ToString = .Item(.Count - 2).ToString Then 
      Return True 
     Else 
      Return False 
     End If 
    End With 

End Function 

如果你的ArrayList是不是有序的,但仍然包含數字的字符串(假設你開始與數字「1」,)那麼下面的功能應該工作:

Private Function OKToInsertUNSorted(ByVal theArrayList As ArrayList, _ 
            ByVal stringToInsert As String) As Boolean 

    If stringToInsert = "1" Then Return True 

    Dim stringToCheck As String = CStr(CInt(stringToInsert) - 1) 

    Dim qry = From stringItem In theArrayList _ 
       Where stringItem.ToString = stringToCheck _ 
       Group By stringItem Into _ 
       stringCount = Count() 

    For Each result In qry 
     If result.stringCount >= 2 Then Return True 
    Next 

    Return False 

End Function 

我在第一個函數中放了很多驗證代碼,這些代碼是基於一些關於你在找什麼的假設,所以你的里程可能會有所不同。

+0

如果stringToInsert =「1」則返回True ???爲什麼這個聲明。 ArrayList可以包含任何不是'1'的數字,或者'1'不可以。 – James123 2010-07-27 13:21:31

+0

這是一個關於你將要存儲的值的假設。假定「1」是有序列表中的第一個值,或者是無序列表中的最低值。如果情況並非如此,請隨時取出:) – knslyr 2010-07-27 13:33:09

+0

您的數據列表中將存儲哪些類型的值?有什麼限制/驗證?什麼範圍? – knslyr 2010-07-27 13:34:40

2

我不太瞭解VB.Net,但也許下面的C#代碼可能會有所幫助(使用LINQ)。

array.Distinct().All(item => array.Count(other => other == item) > 1) 

我猜VB語法(可能是錯誤的)

Array.Distinct().All(Function(item) Array.Count(Function(other) other = item) > 1) 

這裏數組保存你感興趣約

+1

什麼是array.Unique()??? 你想嘗試引用array.Distinct()? – 2010-07-27 07:05:34

+0

是的,這是正確的 - 修正了 – sukru 2010-07-27 08:17:26

+0

儘管如此,ArrayList並不是通用的,並且沒有大多數擴展方法。您需要'.Cast '或'.OfType ',或本地'ArrayList.ToArray()'。 – Kobi 2010-07-27 08:25:21

0

使用下面檢查的數組列表,檢查列表項的項目如果在數組列表中存在重複的數據或不存在

return arrList.ToArray().Distinct().Count() == arrList.Count; 

如果您想檢查之前插入數據是在ArrayList中已經存在或不使用下面的檢查

if (!arrList.Contains(data)) { 
    arrList.Add(data);     
} 
+0

這些都是很好的選擇,但不幸的是OP需要別的東西;如果prev項目存在多次,則只插入新項目。 – Kobi 2010-07-27 08:30:21

-1

您可以簡單地通過檢查數組列表計數和不同的計數。

var isDuplicate = arrayList.Count() > arrayList.Distinct().Count();