如何确定列表 A 是否以相同顺序包含列表 B 中的所有元素?
列表 A 可以包含列表 B 没有的其他元素,但必须按照列表 B 的顺序包含列表 B 的所有元素。
示例 1(列表 A 以 ...、4、0、6 结尾):
List A: List B:
5 2
9 3
2 4
3
4
0
6
这应该返回 True。
示例 2(列表 A 以 ...、0、4、6 结尾):
List A: List B:
5 2
9 3
2 4
3
0
4
6
这应该返回 False。
我找到了这个 answer from JonSkeet to see if List A contains all elements from List B但是,这并不要求它们的顺序相同。
最佳答案
这将获取 ListA
的每个部分并将其与 ListB
与 SequenceEqual
进行比较:
bool containsSameSequence = ListA
.Where((item, index) => index <= ListA.Count - ListB.Count)
.Select((item, index) => ListA.Skip(index).Take(ListB.Count))
.Any(part => part.SequenceEqual(ListB));
它在第一个匹配序列上返回 true
。
关于c# - 检查一个列表是否按顺序包含另一个列表中的所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18037625/