如何检查列表是否包含相同顺序的另一个列表 [英] How to check if list contains another list in same order

查看:72
本文介绍了如何检查列表是否包含相同顺序的另一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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,}; and var 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

这篇关于如何检查列表是否包含相同顺序的另一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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