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

3

5 Answers 5

8

Maybe:

bool equal = collection1.SequenceEqual(collection2);

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

Sign up to request clarification or add additional context in comments.

3 Comments

The OrderBy calls would mean that the order was ignored: but Pramodh wants to see if they are in the same order
yeah sorry, don't know why I initially put those in there :)
+1 great tip - thanks - you saved me from writing some terrible, terrible code!
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;

1 Comment

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.
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)

Comments

0
List<string> list1;
List<string> list2;

bool sameOrder = list1.SequenceEqual(list2);

Comments

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.