6

Sample:

a) 1,2,3,4,5

b) 2,3,4

a contains b.

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

c) 4,3,2

a does not contain c.

Giorgi Nakeuri
  • 35,155
  • 8
  • 47
  • 75
Aminion
  • 465
  • 1
  • 5
  • 13

2 Answers2

3

If you are talking about collections in-memory where the comparisons are simple, you can use something like this (but be warned, the collections are iterated multiple 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 like this:

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
}
Maarten
  • 22,527
  • 3
  • 47
  • 68
2

Since these are strings (and assuming you mean character, not math, strings), why not just join the string Sequences into flattened strings and use String.Contains

var flatA = string.Join(",", MyAs);
var flatB = string.Join(",", MyBs);

return flatA.Contains(flatB);
StuartLC
  • 104,537
  • 17
  • 209
  • 285