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);
2.将序列的每个元素投影到 IEnumerable<T>
,并将结果序列合并为一个序列,并对其中每个元素调用结果选择器函数。
方法:SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>)
原型:
public static System.Collections.Generic.IEnumerable<TResult>
SelectMany<TSource,TCollection,TResult> (this System.Collections.Generic.IEnumerable<TSource> source,
Func<TSource,System.Collections.Generic.IEnumerable<TCollection>> collectionSelector,
Func<TSource,TCollection,TResult> resultSelector);
示例:
//将有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}"));