2013-02-16 181 views
0

我有两个arraylist; list1和list2。它包含arraylist中的对象。检查两个arraylist是否包含相同的元素

如何检查两个arraylist是否包含相同的元素?

我尝试了等于,但它似乎总是返回false。

+2

你不应该使用'ArrayList'。相反,使用通用的'List '。 – svick 2013-02-16 01:23:57

回答

0

如果您必须使用arraylist,您可以将它们转换为IEnumberable,然后使用linq交集。

static bool IsSame(ArrayList source1, ArrayList source2) 
{ 
    var count = source1.Count; 
    // no use comparing if lenghts are different 
    var diff = (count != source2.Count); 
    if (!diff) 
    { 
     // change to IEnumberable<object> 
     var source1typed = source1.Cast<object>(); 
     var source2typed = source2.Cast<object>(); 
     // If intersection is the same count then same objects 
     diff = (source1typed.Intersect(source2typed).Count() == count); 
    } 
    return diff; 
} 
1

而不是使用有些过时System.Collections你应该使用一般的对口System.Collections.Generic。有here描述的各种优点。

您可以创建一个通用的方法来确定两个集合是否相同或不:

Private Function UnanimousCollection(Of T)(ByVal firstList As List(Of T), ByVal secondList As List(Of T)) As Boolean 
    Return firstList.SequenceEqual(secondList) 
End Function 

用法示例:

Dim teachers As List(Of String) = New List(Of String)(New String() {"Alex", "Maarten"}) 
Dim students As List(Of String) = New List(Of String)(New String() {"Alex", "Maarten"}) 
Console.WriteLine(UnanimousCollection(teachers, students)) 
相关问题