温馨提示×

c#中selectmany的使用方法是什么

c#
小亿
109
2024-03-20 16:16:55
栏目: 编程语言

在C#中,SelectMany方法用于将一个序列的每个元素转换为另一个序列,并将所有转换后的序列合并为一个单一的序列。这个方法通常用于处理嵌套的集合数据结构。

List<List<int>> lists = new List<List<int>>
{
    new List<int> {1, 2, 3},
    new List<int> {4, 5, 6},
    new List<int> {7, 8, 9}
};

var flattenedList = lists.SelectMany(list => list);

foreach (var item in flattenedList)
{
    Console.WriteLine(item);
}

在上面的示例中,我们有一个包含多个整数列表的列表。通过使用SelectMany方法,我们将这些嵌套的列表展平为一个单一的整数列表。最终输出结果为1, 2, 3, 4, 5, 6, 7, 8, 9。

0