首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在LINQ Where子句中搜索集合的集合?

在LINQ Where子句中搜索集合的集合,可以使用Lambda表达式和递归方法。以下是一个示例:

代码语言:csharp
复制
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        List<List<int>> nestedList = new List<List<int>>
        {
            new List<int> { 1, 2, 3 },
            new List<int> { 4, 5, 6 },
            new List<int> { 7, 8, 9 }
        };

        int target = 5;
        var result = SearchNestedList(nestedList, target);

        Console.WriteLine($"The target {target} is found in the nested list: {result}");
    }

    static bool SearchNestedList(List<List<int>> nestedList, int target)
    {
        foreach (var list in nestedList)
        {
            if (list.Contains(target))
            {
                return true;
            }
        }

        return false;
    }
}

在这个示例中,我们创建了一个嵌套的整数列表,并使用递归方法SearchNestedList来搜索目标值。如果找到目标值,则返回true,否则返回false

这个示例中没有使用LINQ的Where子句,因为它不适用于嵌套列表。但是,您可以使用LINQ的SelectMany方法将嵌套列表展平,然后使用Where子句来搜索目标值。以下是一个示例:

代码语言:csharp
复制
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        List<List<int>> nestedList = new List<List<int>>
        {
            new List<int> { 1, 2, 3 },
            new List<int> { 4, 5, 6 },
            new List<int> { 7, 8, 9 }
        };

        int target = 5;
        var result = nestedList.SelectMany(x => x).Where(x => x == target).Any();

        Console.WriteLine($"The target {target} is found in the nested list: {result}");
    }
}

在这个示例中,我们使用LINQ的SelectMany方法将嵌套列表展平,然后使用Where子句来搜索目标值。最后,我们使用Any方法来检查是否找到了目标值。如果找到目标值,则返回true,否则返回false

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券