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,263
  • 16
  • 36
Luis Valencia
  • 32,619
  • 93
  • 286
  • 506

4 Answers4

19

You can use SequenceEqual with additional order:

return list1.OrderBy(x => x).SequenceEqual(list2.OrderBy(x => x));
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
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ç
  • 100,147
  • 13
  • 119
  • 184
3

Try this:

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

I hope this helps ;)

Oscar Bralo
  • 1,912
  • 13
  • 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,422
  • 2
  • 21
  • 39