在LINQ Where子句中搜索集合的集合,可以使用Lambda表达式和递归方法。以下是一个示例:
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子句来搜索目标值。以下是一个示例:
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
。
领取专属 10元无门槛券
手把手带您无忧上云