如何找到子列表列表中的指数? [英] How to find index of sublist in list?

查看:142
本文介绍了如何找到子列表列表中的指数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要寻找一些有效的方法(在.NET),如何寻找是否有以字节为单位的一些列表字节序列,如果有任何,索引,其中第一个开始。

I am looking for some efficient way (in .NET), how to find if there is a sequence of bytes in some list of bytes and if there is any, index where the first starts.

例如,让我们说,我有:

For example let's say I have:

var sequence = new List<byte> { 5, 10, 2 };
var listOne = new List<byte> { 1, 3, 10, 5, 10, 2, 8, 9 };
var listTwo = new List<byte> { 1, 3, 10, 5, 2, 10, 8, 9 };

和的结果应该是我的序列是在指数3的那么listOne和索引-1(即它不存在)在listTwo

and the result should be that my sequence is on index 3 in the listOne and on index -1 (ie. it is not there) in the listTwo.

当然,我可以通过列表INT由int和从每一个索引和搜索,如果下面的数字(使用扩展方法为例)符合我的序列,但有一些更有效的方法是什么?环

Of course I can loop through the list int by int and from every index and search if following numbers matches my sequence, but is there some more efficient way (for example using extension methods)?

推荐答案

我觉得最彻底的方法是创建一个这样的通用扩展方法:

I think the cleanest way is create a generic extension method like this:

public static int SubListIndex<T>(this IList<T> list, int start, IList<T> sublist)
{
    for (int listIndex = start; listIndex < list.Count - sublist.Count + 1; listIndex++)
    {
        int count = 0;
        while (count < sublist.Count && sublist[count].Equals(list[listIndex + count]))
            count++;
        if (count == sublist.Count)
            return listIndex;
    }
    return -1;
}

以这种方式来拨打:

to call in this way:

var indexOne = listOne.SubListIndex(0, sequence);
var indexTwo = listTwo.SubListIndex(0, sequence);

P.S。 你也可以从一个给定的索引开始,如果您需要寻找更多的子列表出现

P.S. you can also start from a given index, if you need to search for more sublists occurrences

这篇关于如何找到子列表列表中的指数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆