0

How to Compare Two ArrayList ?

ArrayList l1 = new ArrayList();
l1.Add(1);
l1.Add(2);

And I have another arrayList with same Value .Now I want to Compare both.If Both ArrayList contains same value then return True else False. Is There Any method without loop??

sasjaq
  • 761
  • 1
  • 11
  • 31
Brijesh Gandhi
  • 560
  • 2
  • 10
  • 27

4 Answers4

1

As mentioned in the comments, you can use List instead of ArrayList and then:

l1.SequenceEqual(l2);

I'm assuming l2 is the name of the second list. Also, the values need to be in the same order in both lists for SequenceEqual to return true.

More information here: http://msdn.microsoft.com/en-us/library/bb348567%28v=vs.110%29.aspx

elnigno
  • 1,751
  • 14
  • 37
  • @BrijeshGandhi You have to convert l2 to an Array too. Otherwise you will get a runtime exception. – Marcell Oct 16 '17 at 12:34
0

use the following code:

ArrayList list1 = new ArrayList(new int[] {1,2,3,4,5});

ArrayList list2 = new ArrayList(new int[] {1,2,8});

for (int i=0; i<list1.Count && i<list2.Count; i++)

{

if (!Object.Equals(list1[i], list2[i]))

Console.WriteLine("Different value at index {0}.", i);

}

if (list1.Count > list2.Count)

Console.WriteLine("list1 has more elements than list2.");

if (list2.Count > list1.Count)

Console.WriteLine("list2 has more elements than list1.");

Console.ReadLine();
Adel
  • 1,468
  • 15
  • 18
0

If you are using .NET Framework 4.5, you can use Structural Comparison, as described in MSDN. In your case, since ArrayList hasn't implemented IStructuralEquatable you have to fist create an array instance of your array lists and then use IStructuralEquatable as follows:

ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList();
list1.Add(1);
list2.Add(1);
if ((list1.ToArray() as IStructuralEquatable).Equals(list2.ToArray(), EqualityComparer<int>.Default))
{
    MessageBox.Show("Equal");
}
Arin Ghazarian
  • 5,105
  • 3
  • 23
  • 21
-1

use this code:

ArrayList list1 = new ArrayList(new int[] {1,2});

ArrayList list2 = list1;

for (int i = 0; i < list1.Count; i++)
{
   if(list1[i] == list2[i])
   {
       return true;
   }                
}

return false;
Sohail Ali
  • 468
  • 2
  • 12
  • You obviously haven't tested this. It will return true if the very first two items of the lists are identical and stop checking right there. – Marcell Oct 16 '17 at 12:27