Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if list contains another list in same order

Tags:

c#

list

Is there any simple way in c# to check if list consist of another list?. Here is example, I have:

var list1 = new List<int>() {1, 2, 3, 4, 5, 6,}; and second one var list2 = new List<int>() {5, 6};

this list is a part of first list so it should return true.

var list1 = new List<int>() {1, 2, 3, 4, 5, 6,}; and var list3 = new List<int>() {1, 3}; should return false.

It's not about checking if all elements in first list exist in second list but also about order. It has to have the same order.

like image 859
wgrzesiak147 Avatar asked Jan 03 '16 10:01

wgrzesiak147


People also ask

How do you check if a list is in another list Python in order?

all() method # Program to check the list contains elements of another list # List1 List1 = ['python' , 'javascript', 'csharp', 'go', 'c', 'c++'] # List2 List2 = ['csharp1' , 'go', 'python'] check = all(item in List1 for item in List2) if check is True: print("The list {} contains all elements of the list {}".

How do you check if a list contains items from another list?

There are 2 ways to understand check if the list contains elements of another list. First, use all() functions to check if a Python list contains all the elements of another list. And second, use any() function to check if the list contains any elements of another one.


1 Answers

This works for me:

public bool ContainsSubsequence<T>(List<T> sequence, List<T> subsequence)
{
    return
        Enumerable
            .Range(0, sequence.Count - subsequence.Count + 1)
            .Any(n => sequence.Skip(n).Take(subsequence.Count).SequenceEqual(subsequence));
}

This code uses Enumerable.Range to run through every possible starting point within sequence that could be the same as subsequence, and checks if the segment of sequence the same size as subsequence at this position is actually equal to subsequence.

So for this code:

var list1 = new List<int>() { 1, 2, 3, 4, 5, 6, };
var list2 = new List<int>() { 5, 6, };
var list3 = new List<int>() { 1, 3, };

Console.WriteLine(ContainsSubsequence(list1, list2));
Console.WriteLine(ContainsSubsequence(list1, list3));

I get:

True
False
like image 106
Enigmativity Avatar answered Sep 20 '22 10:09

Enigmativity