2

The two lists are like

          LISTONE    "ONE", "TWO", "THREE"
          LISTTWO    "ONE", "TWO", "THREE"

i need to compare the whether the items in two lists are in same order or not.

Is there any way to do this in LINQ

Thorin Oakenshield
  • 14,232
  • 33
  • 106
  • 146
  • 2
    possible duplicate of [Examining two string arrays for equivalence](http://stackoverflow.com/questions/3250887/examining-two-string-arrays-for-equivalence) – Yuriy Faktorovich Jul 23 '10 at 15:46
  • The SequenceEqual operator (extension method) seems like what you'd want, unless ListOne is allowed to have items that are not in ListTwo or vice-versa. – Dr. Wily's Apprentice Jul 23 '10 at 15:49
  • possible duplicate of [Is there a built-in method to compare collections in C#?](http://stackoverflow.com/questions/43500/is-there-a-built-in-method-to-compare-collections-in-c) – nawfal Nov 08 '13 at 20:27

5 Answers5

8

Maybe:

bool equal = collection1.SequenceEqual(collection2);

See also: Comparing two collections for equality irrespective of the order of items in them

Community
  • 1
  • 1
Matthew Groves
  • 25,181
  • 9
  • 71
  • 121
2

Determine if both lists contain the same data in same order:

bool result = list1.SequenceEqual(list2);

Same entries in different order:

bool result = list1.Intersect(list2).Count() == list1.Count;
Florian Reischl
  • 3,788
  • 1
  • 24
  • 19
  • Watch out with the second version. The `Intersect` method uses set intersection, so you might get unexpected results if one or both of the lists contain duplicates. – LukeH Jul 23 '10 at 15:52
1

If you know there can't be duplicates:

bool result = a.All(item => a.IndexOf(item) == b.IndexOf(item));

Otherwise

bool result = a.SequenceEquals(b)
duraz0rz
  • 387
  • 1
  • 2
  • 10
0
List<string> list1;
List<string> list2;

bool sameOrder = list1.SequenceEqual(list2);
0

These are the correct answers, but as a thought, If you know the lists will have the same data but may be in different order, Why not just sort the lists to guarantee the same order.

var newList = LISTONE.OrderBy(x=>x.[sequence]).ToList();
EKet
  • 7,272
  • 15
  • 52
  • 72