c# - Linq 查询列表包含具有相同顺序的列表

标签 c# linq

考虑我们有这三个列表:

    List<string> l1= new List<string>(){"A","B","C"};
    List<string> l2= new List<string>(){"A","C","B"};

    List<string> l3= new List<string>(){"B","C"};

我需要 LINQ 查询,它说 l1 包含 l3 但 l2 不包含。

最佳答案

为了尊重顺序并考虑到可能的重复元素,您必须枚举序列,一种方法是检查源枚举中的每个开始位置,如果另一个序列从这里开始,例如使用扩展方法:

public static bool ContainsSequence<T>(this IEnumerable<T> source, 
                                       IEnumerable<T> other)
{
    int count = other.Count();

    while (source.Any())
    {
        if (source.Take(count).SequenceEqual(other))
            return true;
        source = source.Skip(1);
    }
    return false;
}

请注意,这将是 O(n2),因为最坏的情况是您已经为 source 中的每个项目完全枚举了 other 枚举收藏。

现在您可以:

List<string> l1 = new List<string>() { "A", "B", "C" };
List<string> l2 = new List<string>() { "A", "C", "B" };
List<string> l3 = new List<string>() { "B", "C" };

bool l1ContainsL2 = l1.ContainsSequence(l2); //returns false
bool l1ContainsL3 = l1.ContainsSequence(l3); //returns true

关于c# - Linq 查询列表包含具有相同顺序的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9183892/

相关文章:

c# - 如何在 Windows RT 中发送击键

c# - 如何从 System.DateTime.Now.Hour 获取 24 小时制?

c# - 我怎样才能从这个 SQLite 操作中减少脂肪?

asp.net - 使用 SQL Server 进行关键字搜索

c# - 将 JSON 字符串反序列化为 Dictionary<string,object>

c# - 如何在我的 Windows Phone 7 应用程序中获取 youtube 视频的缩略图

C# 首次拟合算法输出

C# Linq where 子句

c# - 如何使用 linq 改进查询

C# Linq 查询在一个数组中查找以另一个数组中的字符串结尾的字符串