I know this very similar question has been asked before quite a few times such as in Comparing two collections for equality irrespective of the order of items in them, but I'm trying to use the solutions I'm reading there and something is not working... This HAS to be a stupid mistake I'm making... Please help!!
Ok, so, here's my scenario, suppose I have the following 3 lists created in code:
Dim lst1 as new list(of integer)
Dim lst2 as new list(of integer)
Dim lst3 as new list(of integer)
And then, within the code I end up with, say, the following values in the lists:
lst1: lst2: lst3:
1 1 2
2 2 3
3 3 4
4 4 5
So, obviously, lst1 & lst2 are equal and lst1 & lst3 are not, but what code can I write into my if statement to verify this?
I've tried:
lst1.SequenceEqual(lstXX)
And that returns True for both lst2 and lst3 I've tried:
lst1.Equals(lstXX)
And that returns False for both lst2 and lst3
Now, I know I could do it with code comparing count and lst1.Except(lstXX), but I'm wondering more so what I'm doing wrong here and even more importantly, what is the most efficient method to do this??
Thanks!!!
equals() method. A simple solution to compare two lists of primitive types for equality is using the List. equals() method. It returns true if both lists have the same size, and all corresponding pairs of elements in both lists are equal.
Python sort() method and == operator to compare lists We can club the Python sort() method with the == operator to compare two lists. Python sort() method is used to sort the input lists with a purpose that if the two input lists are equal, then the elements would reside at the same index positions.
You can compare two array lists using the equals() method of the ArrayList class, this method accepts a list object as a parameter, compares it with the current object, in case of the match it returns true and if not it returns false.
Method 2 : Using collections.Counter() Using Counter() , we usually are able to get frequency of each element in list, checking for it, for both the list, we can check if two lists are identical or not.
Assuming you want ordering to be important, SequenceEqual
is exactly what you want - and in the sample you've given, lst1.SequenceEqual(lst3)
will return false. Here's a short but complete program to demonstrate:
using System;
using System.Collections.Generic;
using System.Linq;
class Test
{
static void Main(string[] args)
{
var lst1 = new List<int> { 1, 2, 3, 4 };
var lst2 = new List<int> { 1, 2, 3, 4 };
var lst3 = new List<int> { 2, 3, 4, 5 };
Console.WriteLine(lst1.SequenceEqual(lst2)); // True
Console.WriteLine(lst1.SequenceEqual(lst3)); // False
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With