【问题标题】:Check whether two arraylists contains the same elements检查两个数组列表是否包含相同的元素
【发布时间】:2013-02-16 01:17:23
【问题描述】:

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

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

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

【问题讨论】:

  • 你不应该使用ArrayList。相反,请使用通用的List<T>

标签: .net vb.net arraylist


【解决方案1】:

您应该使用通用的对应物System.Collections.Generic,而不是使用有些过时的System.Collectionshere 描述了各种优点。

你可以创建一个泛型方法来判断两个集合是否相同:

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

【讨论】:

    【解决方案2】:

    如果你必须使用 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-18
      • 2019-08-24
      • 2012-08-21
      • 1970-01-01
      • 2019-04-27
      • 1970-01-01
      • 2012-05-17
      • 2014-07-29
      相关资源
      最近更新 更多