问题描述
C#中是否有任何简单的方法来检查列表是否包含另一个列表?这是例子我有:
Is there any simple way in c# to check if list consist of another list?.Here is example,I have:
var list1 = new List<int>() {1, 2, 3, 4, 5, 6,};
第二个var list2 = new List<int>() {5, 6};
此列表是第一个列表的一部分,因此应返回true.
this list is a part of first list so it should return true.
var list1 = new List<int>() {1, 2, 3, 4, 5, 6,};
和var list3 = new List<int>() {1, 3};
应该返回false.
var list1 = new List<int>() {1, 2, 3, 4, 5, 6,};
andvar list3 = new List<int>() {1, 3};
should return false.
不是要检查第一个列表中的所有元素是否都存在于第二个列表中,而是要检查顺序.它必须具有相同的顺序.
It's not about checking if all elements in first list exist in second list but also about order. It has to have the same order.
推荐答案
这对我有用:
public bool ContainsSubsequence<T>(List<T> sequence, List<T> subsequence)
{
return
Enumerable
.Range(0, sequence.Count - subsequence.Count + 1)
.Any(n => sequence.Skip(n).Take(subsequence.Count).SequenceEqual(subsequence));
}
此代码使用Enumerable.Range
遍历sequence
中可能与subsequence
相同的每个可能的起点,并检查sequence
的段与该位置上与subsequence
相同的大小是否实际上等于subsequence
.
This code uses Enumerable.Range
to run through every possible starting point within sequence
that could be the same as subsequence
, and checks if the segment of sequence
the same size as subsequence
at this position is actually equal to subsequence
.
因此,此代码:
var list1 = new List<int>() { 1, 2, 3, 4, 5, 6, };
var list2 = new List<int>() { 5, 6, };
var list3 = new List<int>() { 1, 3, };
Console.WriteLine(ContainsSubsequence(list1, list2));
Console.WriteLine(ContainsSubsequence(list1, list3));
我得到:
True
False
这篇关于如何检查列表是否包含相同顺序的另一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!