3

I have the following 2 objects

List<string> list1
List<string> list2

On list 1 I have 3 items On list 2 I have the same 3 items in a different order.

I need a simple method to return that both lists are equal when they contain the same elements regardless of order

SeeMoreGain
  • 1,223
  • 16
  • 36
Luis Valencia
  • 29,595
  • 84
  • 264
  • 467

4 Answers4

19

You can use SequenceEqual with additional order:

return list1.OrderBy(x => x).SequenceEqual(list2.OrderBy(x => x));
MarcinJuraszek
  • 121,297
  • 15
  • 183
  • 252
5

You can use All and Contains method like this, this will return true if both lists contains same elements even if the order is different:

bool control = list1.All(x => list2.Contains(x) && 
                          list1.Count(a => a == x) == list2.Count(b => b == x));
Selman Genç
  • 97,365
  • 13
  • 115
  • 182
3

Try this:

bool equals = list1.OrderBy(x => x).SequenceEqual(list2.OrderBy(y => y));

I hope this helps ;)

Oscar Bralo
  • 1,904
  • 12
  • 12
0

You should consider using a HashSet, rather than a List. Its a little less expensive:

HashSet<string> firstSet = new HashSet<string>();
HashSet<string> secondSet = new HashSet<string>();

PopulateSets(firstSet, secondSet); //Example of method you might use to populate your hashsets.

bool isEqual = firstSet.SetEquals(secondSet);

From MSDN:

The SetEquals method ignores duplicate entries and the order of elements in the other parameter.

Ray
  • 1,394
  • 2
  • 18
  • 37