深入理解 LINQ 中的 SelectMany

发布时间 2023-11-13 10:51:46作者: 朦朦胧胧的月亮最美好

在LINQ(Language Integrated Query)中,SelectMany 是一个强大的方法,用于处理集合中的嵌套结构。本文将深入探讨 SelectMany 的用法,以及在其两种形式中参数的含义。

1. SelectMany 的单参数形式

IEnumerable<TResult> SelectMany<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, IEnumerable<TResult>> selector);

这种形式的 SelectMany 接受两个参数:源集合和一个返回集合的转换函数。让我们通过一个例子来说明:

List<List<int>> listOfLists = new List<List<int>> { new List<int> { 1, 2, 3 }, new List<int> { 4, 5, 6 } }; List<int> flattenedList = listOfLists.SelectMany(list => list).ToList();

在这个例子中,SelectMany 将所有嵌套列表的元素合并为一个单一的列表。

2. SelectMany 的双参数形式

IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(this IEnumerable<TSource> source, Func<TSource, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector);

这种形式的 SelectMany 接受三个参数:源集合、返回集合的转换函数和对结果进行最终转换的函数。以下是一个例子:

List<int> numbers = new List<int> { 1, 2, 3 }; var pairs = numbers.SelectMany( x => new[] { $"{x} is odd", $"{x} is even" }, (number, description) => $"{number}: {description}" ).ToList();

SelectMany 中,resultSelector 参数接受两个参数,分别对应源元素和集合元素。在我的例子中,numbers 是源集合,而 new[] { $"{x} is odd", $"{x} is even" } 返回的集合中的每个元素都是一个字符串,因此 (number, description) 中的 number 对应 numbers 中的元素,而 description 对应集合中的每个字符串。

具体来说,在这个例子中:

  • numbers 中的每个元素(称为 x)都会与 new[] { $"{x} is odd", $"{x} is even" } 中的每个字符串进行组合。
  • 对于 number,它是 numbers 中的元素。
  • 对于 description,它是 new[] { $"{x} is odd", $"{x} is even" } 中的每个字符串。

在这个例子中,SelectMany 将每个数字与一个字符串集合进行组合,并应用最终的转换操作。

结论

SelectMany 是 LINQ 中强大的方法之一,用于处理嵌套结构。通过深入理解其两种形式及其参数,您可以更灵活地应用它来解决各种问题。

希望这篇文章能够帮助您更好地理解和应用 SelectMany。如有任何疑问或建议,请随时在评论中提出。