在另一个列表中查找列表

Find list in another list

有没有一种简单的方法可以在另一个列表中找到一个列表,同时考虑顺序? (除了遍历它们。)基本上就像 String 的 .IndexOf 工作方式一样。

string[] lookInThis = { "a", "b", "c", "d" };
string[] lookForThis1 = { "b", "c" };
string[] lookForThis2 = { "b", "d" };

int FoundLoc = string.Join(",", lookInThis).IndexOf(string.Join(",", lookForThis1));

这适用于我的琴弦,但感觉还可以改进。

在我的示例中,这些是我的预期输出:

lookForThis1   1
lookForThis2  -1 or something like that.

这应该可以满足您的要求。不太漂亮,因为我只是把它放在一起而且我不是 LINQ 精灵:

    public int SublistIndex(string[] lookInThis, string[]lookForThis)
    {
        int i;
        for (i = 0; i < lookInThis.Count(); i++)
        {
            if (lookInThis.ElementAt(i).Equals(lookForThis.First()))
            {
                //Found the first element of the list we are searching for
                int j;

                //Now we need to check if the other elements are there in correct order
                for (j = 0; j < lookForThis.Count(); j++)
                {
                    if (i + j == lookInThis.Count())
                    {
                        //Reached the end of the lookInThis list with no match
                        return -1;
                    }
                    if (!lookInThis.ElementAt(i + j).Equals(lookForThis.ElementAt(j)))
                    {
                        //Sequence is not identical, stop inner loop
                        break;
                    }
                }
                if (j == lookForThis.Count())
                {
                    //found it!
                    return i;
                }
            }
        }
        //reached the end and didn't find it
        return -1;
    }

用这个测试:

        string[] t1 = { "a", "b", "c" };
        string[] t2 = { "b", "c" };
        string[] t3 = { "b", "d" };
        int tt1 = SublistIndex(t1, t2);
        int tt2 = SublistIndex(t1, t3);

tt1 = 1tt2=-1

您基本上可以用 string 替换任何类型,前提是您还将 .equals() 比较更改为适当的比较。

工作原理:

它循环遍历 lookInThis,当找到 lookForThis 的起始元素时,它开始另一个循环来比较它们。如果它发现任何元素不匹配,它会中断此循环并恢复。如果它到达 lookForThis 的结尾,它 returns 第一个循环的索引。当它到达lookInThis的末尾时它returns-1。又快又脏,所以可能不建议使用大列表。