1.Select 和 SelectMany 方法
SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TResult>>)
将序列的每个元素投影到 IEnumerable
1. 使用 SelectMany<TSource,TResult>(IEnumerable, Func<TSource,IEnumerable>) 对数组执行一对多投影。
PetOwner[] petOwners =
{ new PetOwner { Name="Higa, Sidney",
Pets = new List<string>{ "Scruffy", "Sam" } },
new PetOwner { Name="Ashkenazi, Ronen",
Pets = new List<string>{ "Walker", "Sugar" } },
new PetOwner { Name="Price, Vernette",
Pets = new List<string>{ "Scratches", "Diesel" } } };
// 使用 SelectMany() 查询
IEnumerable<string> query1 = petOwners.SelectMany(petOwner => petOwner.Pets);
// 使用 Select() 查询达到使用 SelectMany() 的查询效果
IEnumerable<List<String>> query2 =
petOwners.Select(petOwner => petOwner.Pets);
//将有1对多关系的两个集合,合并输出为一个集合
var query3 = petOwners.SelectMany(petOwner => petOwner.Pets, (owner, pet) => new { OwnerName = owner.Name, Pet = pet });
query3.ToList().ForEach(x => Console.WriteLine($"{x.OwnerName}:{x.Pet}"));
标签:petOwner,Name,补充,IEnumerable,Linq,学习,Pets,new,SelectMany
From: https://www.cnblogs.com/hrx521/p/18138990