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

c#, linq, list

Solution

Here's a quick way:

var equal = listA.Count - listB.Count < 0 
    ? false 
    : Enumerable.Range(0, listA.Count - listB.Count).Any(i => 
      listA.Skip(i).Take(listB.Count).SequenceEqual(listB));

However, I'd prefer to use an extension method like this:

public static bool ContainsSequence<T>(this IEnumerable<T> outer, 
                                       IEnumerable<T> inner)
{
    var innerCount = inner.Count();
    for(int i = 0; i < outer.Count() - innerCount; i++)
    {
        if(outer.Skip(i).Take(innerCount).SequenceEqual(inner))
            return true;
    }

    return false;
 }

which you can call like:

var equals = listA.ContainsSequence(listB);

And here's a more efficient version of the same extension method specific to `List<T>`:

public static bool ContainsSequence<T>(this List<T> outer, List<T> inner)
{
    var innerCount = inner.Count;

    for (int i = 0; i < outer.Count - innerCount; i++)
    {
        bool isMatch = true;
        for (int x = 0; x < innerCount; x++)
        {
            if (!outer[i + x].Equals(inner[x]))
            {
                isMatch = false;
                break;
            }
        }

        if (isMatch) return true;
    }

    return false;
}

Problem

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.

Original source

Related problems