本文主要是介绍.Net C# Linq SelectMany 方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在开发过程中经常遇到嵌套的数据结构,往往需要我们循环套循环的取出结果,代码长还不方便阅读,Linq中的SelectMany方法就是用来处理这类情况的,我们看下示例代码。
参考代码:
这段参考代码是获取 Homes集合中 Animals 集合的结果并输出动物的名字。
public static void LinqSelectManyMain(){DataList data = new();{//获取家里动物的名字List<string> nameList = new List<string>();foreach (var Home in data.Homes){foreach (var Animal in Home.Animals){nameList.Add(Animal.Name);}}//输出动物名字Console.WriteLine($"双层循环输出-{string.Join(" ", nameList)}");}{//获取家里动物的名字List<string> nameList = new List<string>();//SelectMany可以把结果中多个集合合并为一个结果并返回List<Animal> Animals = data.Homes.SelectMany(h => h.Animals).ToList();foreach (var Animal in Animals){nameList.Add(Animal.Name);}//输出动物名字Console.WriteLine($"使用SelectMany方法加一层循环输出-{string.Join(" ", nameList)}");}{//获取家里动物的名字List<string> nameList = data.Homes.SelectMany(h => h.Animals).Select(a => a.Name).ToList();//输出动物名字Console.WriteLine($"使用SelectMany方法加Select方法输出-{string.Join(" ", nameList)}");}{List<string> nameList = data.Homes.SelectMany(h => h.Animals, (home, animal) => animal.Name).ToList();//输出动物名字Console.WriteLine($"使用SelectMany方法输出-{string.Join(" ", nameList)}");}{//获取家里动物的名字List<string> nameList = new List<string>();//此处对比Select方法和SelectMany方法的区别List<List<Animal>> AList = data.Homes.Select(s => s.Animals).ToList();foreach (var animals in AList){foreach (var animal in animals){nameList.Add(animal.Name);}}//输出动物名字Console.WriteLine($"Select方法加双层循环输出-{string.Join(" ", nameList)}");}}
输出结果:
这里补充说明下Select方法和SelectMany方法的区别;
Select方法 :获取集合中的元素并将元素“合并到”一个结果集合中
SelectMany方法 :获取集合中的元素并将元素“合并为”一个结果集合中
例如:
//此处对比Select方法和SelectMany方法的区别List<List<Animal>> AList = data.Homes.Select(s => s.Animals).ToList();//SelectMany可以把结果中多个集合合并为一个结果并返回List<Animal> Animals = data.Homes.SelectMany(h => h.Animals).ToLis();
这篇关于.Net C# Linq SelectMany 方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!