Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine, that sequence contains other sequence, in same order, with using LINQ [duplicate]

Tags:

c#

linq

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.

like image 894
Aminion Avatar asked May 28 '15 09:05

Aminion


2 Answers

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
}
like image 114
Maarten Avatar answered Oct 01 '22 21:10

Maarten


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);
like image 38
StuartLC Avatar answered Oct 01 '22 22:10

StuartLC