0

我有两个数组列表;清单 1 和清单 2。它包含数组列表中的对象。

如何检查两个数组列表是否包含相同的元素?

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

4

2 回答 2

1

而不是使用有点弃用的System.Collections,你应该使用通用的对应物System.Collections.Generic这里描述了各种优点。

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

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))
于 2013-02-16T07:26:58.437 回答
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;
}
于 2013-02-16T01:26:21.213 回答