I have two lists as below, how can I say that they have the same elements. The order is not important.
var list1 = new List<int> {1,2,3};
var list2 = new List<int> {2,1,3};
How can I say that these are equal? Should I write my own method or is there a built-in method for it?
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. But this method also ignores the ordering of the elements in the list and only takes into account the frequency of elements.
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.
That's what sets (e.g., HashSet<T>
) are for. Sets have no defined order, and SetEquals
verifies whether the set and another collection contain the same elements.
var set = new HashSet<int>(list1);
var equals = set.SetEquals(list2);
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