如何使用 LINQ C# 展平列表?
展平列表是指将 List<List<T>> 转换为 List<T>。例如,让我们考虑一个 List<List<int>>,需要将其转换为 List<int>。
LINQ 中的 SelectMany 用于将序列的每个元素投影到 IEnumerable<T> 中,然后将结果序列展平为一个序列。这意味着 SelectMany 运算符将结果序列中的记录合并,然后将其转换为一个结果。
使用 SelectMany
示例
using System;
using System.Collections.Generic;
using System.Linq;
namespace DemoApplication{
public class Program{
static void Main(string[] args){
List<List<int>> listOfNumLists = new List<List<int>>{
new List<int>{
1, 2
},
new List<int>{
3, 4
}
};
var numList = listOfNumLists.SelectMany(i => i);
Console.WriteLine("Numbers in the list:");
foreach(var num in numList){
Console.WriteLine(num);
}
Console.ReadLine();
}
}
}输出
Numbers in the list: 1 2 3 4
使用查询
示例
using System;
using System.Collections.Generic;
using System.Linq;
namespace DemoApplication{
public class Program{
static void Main(string[] args){
List<List<int>> listOfNumLists = new List<List<int>>{
new List<int>{
1, 2
},
new List<int>{
3, 4
}
};
var numList = from listOfNumList in listOfNumLists
from value in listOfNumList
select value;
Console.WriteLine("Numbers in the list:");
foreach(var num in numList){
Console.WriteLine(num);
}
Console.ReadLine();
}
}
}输出
Numbers in the list: 1 2 3 4
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP