检查如果一个列表包含从另一个列表中,以便所有项目 [英] Check if one list contains all items from another list in order
问题描述
我如何判断列表A包含了所有由B组以相同的顺序的元素?
How can I determine if List A contains all of the elements from List B in the same order?
表A可以有表B没有更多的元素,但必须包含在该列表B有它们的顺序列表B中的所有元素。
List A can have additional elements that List B does not have, but must contain all elements of List B in the order that List B has them.
示例1 (列表A 的用的结束... < STRONG> 4,0, 6 ):
Example 1 (List A ending with ..., 4, 0, 6):
List A: List B:
5 2
9 3
2 4
3
4
0
6
这应该返回真
示例2 (列表A 的结尾的 ... 0,4 6 的):
Example 2 (List A ending with ..., 0, 4, 6):
List A: List B:
5 2
9 3
2 4
3
0
4
6
这应该返回<强>假
我发现这个的回答JonSkeet,看看列表A中包含由b组的所有元素然而,不要求他们在相同的顺序
I found this answer from JonSkeet to see if List A contains all elements from List B however, that does not require them to be in the same order.
推荐答案
下面是一个简单的方法:
Here's a quick way:
var equal = listA.Count - listB.Count < 0
? false
: Enumerable.Range(0, listA.Count - listB.Count).Any(i =>
listA.Skip(i).Take(listB.Count).SequenceEqual(listB));
不过,我更愿意使用延长方法是这样的:
However, I'd prefer to use an extension method like this:
public static bool ContainsSequence<T>(this IEnumerable<T> outer,
IEnumerable<T> inner)
{
var innerCount = inner.Count();
for(int i = 0; i < outer.Count() - innerCount; i++)
{
if(outer.Skip(i).Take(innerCount).SequenceEqual(inner))
return true;
}
return false;
}
您可以拨打如下:
which you can call like:
var equals = listA.ContainsSequence(listB);
这是一个更加的有效特定版本相同的扩展方法来列表< T>
:
And here's a more efficient version of the same extension method specific to List<T>
:
public static bool ContainsSequence<T>(this List<T> outer, List<T> inner)
{
var innerCount = inner.Count;
for (int i = 0; i < outer.Count - innerCount; i++)
{
bool isMatch = true;
for (int x = 0; x < innerCount; x++)
{
if (!outer[i + x].Equals(inner[x]))
{
isMatch = false;
break;
}
}
if (isMatch) return true;
}
return false;
}
这篇关于检查如果一个列表包含从另一个列表中,以便所有项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!