24

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}

Graviton
  • 81,782
  • 146
  • 424
  • 602
  • @280Z28: so you voted down a question because of the answers? Doesn't sound very reasonable. – Graviton Oct 27 '09 at 06:15
  • 1
    The SetEquals of HashSet is best suited for checking whether two sets are equal as defined in this question – LCJ Dec 02 '12 at 09:25

4 Answers4

42
var same = list1.Except(list2).Count() == 0 && 
           list2.Except(list1).Count() == 0;
leppie
  • 115,091
  • 17
  • 196
  • 297
9

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));
Sam Harwell
  • 97,721
  • 20
  • 209
  • 280
4

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)
Community
  • 1
  • 1
LCJ
  • 22,196
  • 67
  • 260
  • 418
  • 2
    Using HashSets seems like the most elegant way to do this (and probably pretty fast too.) – ThisGuy Dec 22 '13 at 06:14
  • Only if you rely on hash to be unique. I guess that with the right hash it will be unique for the numbers it can represent - but then it shouldn't be faster. – LosManos Oct 17 '22 at 05:09
1

You need to get the intersection of the two lists:

bool areIntersected = t1.Intersect(t2).Count() > 0;

In response to you're modified question:

bool areSameIntersection = t1.Except(t2).Count() == 0 && t2.Except(t1).Count() == 0;
jrista
  • 32,447
  • 15
  • 90
  • 130