Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ: check whether two list are the same

Tags:

This should be easy.

I want to check whether two list are the same in that they contain all the same elements or not, orders not important.

Duplicated elements are considered equal, i.e.e, new[]{1,2,2} is the same with new[]{2,1}

like image 392
Graviton Avatar asked Oct 27 '09 03:10

Graviton


People also ask

How do you check if two lists have the same element in Python?

Using sets Another approach to find, if two lists have common elements is to use sets. The sets have unordered collection of unique elements. So we convert the lists into sets and then create a new set by combining the given sets. If they have some common elements then the new set will not be empty.


3 Answers

var same = list1.Except(list2).Count() == 0 && 
           list2.Except(list1).Count() == 0;
like image 179
leppie Avatar answered Oct 20 '22 20:10

leppie


Edit: This was written before the OP added that { 1, 2, 2 } equals { 1, 1, 2 } (regarding handling of duplicate entries).

This will work as long as the elements are comparable for order.

bool equal = list1.OrderBy(x => x).SequenceEqual(list2.OrderBy(x => x));
like image 40
Sam Harwell Avatar answered Oct 20 '22 21:10

Sam Harwell


The SetEquals of HashSet is best suited for checking whether two sets are equal as defined in this question

        string stringA = "1,2,2";
        string stringB = "2,1";

        HashSet<string> setA = new HashSet<string>((stringA.Trim()).Split(',').Select(t => t.Trim()));
        HashSet<string> setB = new HashSet<string>((stringB.Trim()).Split(',').Select(t => t.Trim()));

        bool isSetsEqual = setA.SetEquals(setB);

REFERENCE:

  1. Check whether two comma separated strings are equal (for Content set)
like image 44
LCJ Avatar answered Oct 20 '22 19:10

LCJ