C# 中的 SelectMany 方法主要用于處理集合,特別是那些實現了 IEnumerable 接口的集合。它可以對集合中的每個元素執行一個指定的操作,并將這些操作的結果合并成一個新的集合。
SelectMany 的主要應用場景是當你需要對集合中的每個元素執行一個操作,并將這些操作的結果合并成一個單一的、扁平化的集合時。例如,你可以使用 SelectMany 來將嵌套的集合展平為一個單一的集合。
下面是一個簡單的示例,演示了如何使用 SelectMany 來展平一個嵌套的集合:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// 創建一個嵌套的集合
var nestedCollection = new List<List<int>>
{
new List<int> { 1, 2, 3 },
new List<int> { 4, 5, 6 },
new List<int> { 7, 8, 9 }
};
// 使用 SelectMany 展平嵌套的集合
var flattenedCollection = nestedCollection.SelectMany(innerList => innerList);
// 輸出展平后的集合
Console.WriteLine("Flattened collection:");
foreach (var item in flattenedCollection)
{
Console.WriteLine(item);
}
}
}
在這個示例中,我們首先創建了一個嵌套的集合 nestedCollection,其中包含三個子列表。然后,我們使用 SelectMany 方法來展平這個嵌套的集合,并將結果存儲在 flattenedCollection 中。最后,我們遍歷并輸出展平后的集合。