Linq C# 中的 Select 和 SelectMany 有什么区别?
csharpserver side programmingprogramming更新于 2025/10/2 11:22:17
Select 运算符会为每个源生成一个结果值。SelectMany 运算符属于投影运算符类别。它用于将序列中的每个元素投影到 IEnumerable 对象,并将结果序列展平为一个序列。
示例
class Demo{
public string Name { get; set; }
public List<string> Contents { get; set; }
public static List<Demo>GetAllContents(){
List<Demo> listContents = new List<Demo>{
new Demo{
Name = "Cap",
Contents = new List<string> { "Nike", "Adidas" }
},
new Demo{
Name = "Shoes",
Contents = new List<string> { "Nike", "Puma", "Adidas" }
},
};
return listContents;
}
}
class Program{
static void Main(){
IEnumerable<List<string>> result = Demo.GetAllContents().Select(s => s.Contents);
foreach (List<string> stringList in result){
foreach (string str in stringList){
Console.WriteLine(str);
}
}
Console.WriteLine("---Select Many---")
IEnumerable<string> resultSelectMany = Demo.GetAllContents().SelectMany(s => s.Contents);
foreach (string str in resultSelectMany){
Console.WriteLine(str);
}
Console.ReadKey();
}
}
输出
Nike Adidas Nike Puma Adidas ---Select Many--- Nike Adidas Nike Puma Adidas

