Linq補充學習

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}"));
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章