c# – 如何确定一个数组是另一个数组的一部分?

例如:我有阵列

var src = new byte[] {1, 2, 3, 4, 5};
var tag = new byte[] {3, 4};

谁知道快速查找标签数组索引的方法?
我需要以下内容:

int FindIndexOfSeq(byte[] src, byte[] sequence);

一个序列在src中可以多次出现.

解决方案:How to find index of sublist in list?

最佳答案
int FindIndexOfSeq<T>(byte[] src, byte[] tag)
{
    Int32 tagCount = tag.Count();            

    // If `tag` is not empty and `src` contains `tag`
    if (tagCount > 0 && src.Intersect(tag).Count() == tagCount)
    {
        // Find index of first element in `tag`
        Int32 tagStartIndex = Array.IndexOf(src, tag.First());

        // Get the matching slice of `tag` from `src`
        var newSrc = src.Skip(tagStartIndex).Take(tag.Count()).ToList();

        // Zip them together using their difference
        var sum = Enumerable.Zip(tag, newSrc, (i1, i2) => Convert.ToInt32(i2 - i1)).Sum();

        // If total of their differences is zero, both sequences match
        if (sum == 0)
        {
            // return starting index of `tag` in `src`
            return tagStartIndex;
        }
    }

    // return `Not Found`
    return -1;
}

转载注明原文:c# – 如何确定一个数组是另一个数组的一部分? - 代码日志