【发布时间】:2013-02-16 01:17:23
【问题描述】:
我有两个数组列表;清单 1 和清单 2。它包含数组列表中的对象。
如何检查两个数组列表是否包含相同的元素?
我尝试了equals,但它似乎总是返回false。
【问题讨论】:
-
你不应该使用
ArrayList。相反,请使用通用的List<T>。
我有两个数组列表;清单 1 和清单 2。它包含数组列表中的对象。
如何检查两个数组列表是否包含相同的元素?
我尝试了equals,但它似乎总是返回false。
【问题讨论】:
ArrayList。相反,请使用通用的List<T>。
您应该使用通用的对应物System.Collections.Generic,而不是使用有些过时的System.Collections。 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))
【讨论】:
如果你必须使用 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;
}
【讨论】: