Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if one list contains all items from another list in order

Tags:

c#

list

linq

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.

like image 999
Ricketts Avatar asked Aug 03 '13 21:08

Ricketts


1 Answers

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.

like image 186
Tim Schmelter Avatar answered Oct 16 '22 22:10

Tim Schmelter