Determine that this sequence contains a different sequence, in the same order, using LINQ

Example:

a) 1,2,3,4,5

b) 2,3,4

a contains b.

Unlike .Intersect() , I need to keep the sequence order, i.e.

c) 4.3.2

a does not contain c.

+5
source share
2 answers

If you are talking about collections in memory where comparisons are simple, you can use something like this (but be careful, collections are repeated several times!):

 public static bool Contains<T>(this IEnumerable<T> data, IEnumerable<T> otherData) { var dataLength = data.Count(); var otherDataLength = otherData.Count(); if (dataLength < otherDataLength) return false; return Enumerable.Range(0, dataLength - otherDataLength + 1) .Any(skip => data.Skip(skip).Take(otherDataLength).SequenceEqual(otherData)); } 

And use it as follows:

 var a1 = new List<int> { 1, 2, 3, 4, 5 }; var a2 = new List<int> { 2, 3, 4}; var a3 = new List<int> { 4, 3, 2}; if (a1.Contains(a2)) { // is hit } if (a1.Contains(a3)) { // is not hit } 
+3
source

Since these are strings (and assuming that you mean a character, not math, strings), why not just join a sequence of strings in flattened strings and use String.Contains

 var flatA = string.Join(",", MyAs); var flatB = string.Join(",", MyBs); return flatA.Contains(flatB); 
+2
source

All Articles