在List中查找序列

时间:2010-03-11 21:16:13

标签: c# linq generics list

我有一个整数列表,我想搜索一个序列。

例如,如果我有一个主列表: 1,2,3,4,9,2,39,482,19283,19,23,2,29

我想找到序列: 1,2,3,4

我想用一些简单的方法来填充子列表: 1,2,3,4 +主列表中接下来的五个整数

然后从主列表中删除子集列表中的整数,这样在操作结束时,我的列表将如下所示:

主列表: 19,23,1,29

子集列表: 1,2,3,4,9,2,39,482,19283

希望这是有道理的。我猜也许LINQ会对这样的东西有好处,但我以前从未使用它。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

您可以从编写可以在列表中找到子列表的函数IndexOfSublist开始。之前已经多次询问过这个问题。

假设您已实施IndexOfSublist,请使用它来查找结果的第一个元素,然后您可以使用GetRange选择要保留的元素,然后RemoveRange从原始列表中删除元素。

List<int> l = new List<int> { 1, 1, 2, 3, 4, 9, 2, 39, 482, 19283, 19, 23, 1, 29 };
List<int> needle = new List<int> { 1, 2, 3, 4 };

int i = indexOfSubList(l, needle);
if (i != -1)
{
    // TODO: What should we do if there are fewer than four
    // elements left after the needle? Currently we just throw.
    List<int> result = l.GetRange(i, needle.Count + 4);
    l.RemoveRange(i, result.Count);
    // TODO: Do something with the result;
}

答案 1 :(得分:0)

<强> HINT

你可以尝试这样的东西以及迭代器:

List<int> n = new List<int>() { 1, 2, 3, 4, 9, 2, 39, 482, 19283, 19, 23, 1, 29 };
List<int> toFind = new List<int>() { 1, 2, 3, 4 };

if (n.Skip(indextostart).Take(4).ToList()==toFind)
{
    n.RemoveRange(indextostart,4);
}
相关问题