Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if two list have the same items

Tags:

c#

list

linq

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?

like image 679
Vahid Avatar asked Jun 23 '14 08:06

Vahid


People also ask

How do you know if two lists have the same element?

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.

How can you tell if two ArrayList has the same element?

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.


1 Answers

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);
like image 69
dcastro Avatar answered Oct 03 '22 21:10

dcastro