检查两个arraylists是否包含相同的元素

时间:2013-02-16 01:17:24

标签: .net vb.net arraylist

我有两个arraylist; list1和list2。它包含arraylist中的对象。

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

我尝试使用equals,但似乎它总是返回false。

2 个答案:

答案 0 :(得分:1)

您应该使用通用对应的System.Collections,而不是使用稍微弃用的System.Collections.Generichere描述了各种优点。

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

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))

答案 1 :(得分:0)

如果你必须使用arraylist,你可以将它们转换为IEnumerable,然后使用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;
}