How can I determine if List A contains all of the elements from List B in the same order?
List A can have additional elements that List B does not have, but must contain all elements of List B in the order that List B has them.
Example 1 (List A ending with ..., 4, 0, 6):
List A: List B:
5 2
9 3
2 4
3
4
0
6
This should return True.
Example 2 (List A ending with ..., 0, 4, 6):
List A: List B:
5 2
9 3
2 4
3
0
4
6
This should return False.
I found this answer from JonSkeet to see if List A contains all elements from List B however, that does not require them to be in the same order.
This takes each part of ListA
and compares it with ListB
with SequenceEqual
:
bool containsSameSequence = ListA
.Where((item, index) => index <= ListA.Count - ListB.Count)
.Select((item, index) => ListA.Skip(index).Take(ListB.Count))
.Any(part => part.SequenceEqual(ListB));
Demo
It returns true
on the first matching sequence.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With