Thanks to @GeorgeVovos and @Enigmativity for pointing out problems in the first solution.
public static bool HasSubSequence(List<int> main, List<int> query) { var startIndex = main.IndexOf(query.First()); if (main == null || query == null || startIndex < 0) return false; while (startIndex >= 0) { if (main.Count - startIndex < query.Count) return false; var nonMatch = false; for (int i = 0; i < query.Count; i++) { if (main[i + startIndex] != query[i]) { main = main.Skip(startIndex + 1).ToList(); startIndex = main.IndexOf(query.First()); nonMatch = true; break; } } if (!nonMatch) return true; } return false; }
Example
var l1 = new List<int> { 1, 2, 3, 4, 5 }; var l2 = new List<int> { 4, 5 }; var l3 = new List<int> { 1, 3 }; var l4 = new List<int> { 5, 6 }; var l5 = new List<int> { 1, 2, 3, 2, 5, 6, 2, 4, 8 }; var l6 = new List<int> { 2, 4 }; var test1 = HasSubSequence(l1, l2);
source share