星期日, 9月 30, 2018

[LINQ] SelectMany

筆記利用 SelectMany() 來產生類似 TSQL JOIN 效果
namespace SelectManySample
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("===== MSDN 寫法 =====");

            var msdn = DemoHelper.GetDate()
                .SelectMany(
                    OwnerPet => OwnerPet.Pets,
                    (petOwner, petName) => new { petOwner, petName })
                .Where(w => w.petName.StartsWith("S"))
                .Select(ownerAndPet => new Result
                {
                    PetOwner = ownerAndPet.petOwner.Name,
                    PetName = ownerAndPet.petName
                });

            DemoHelper.ShowData(msdn);

            Console.WriteLine("===== 巢狀寫法 =====");

            var Nested = DemoHelper.GetDate()
                .SelectMany(p => p.Pets.Select(Pet => new Result { PetOwner = p.Name, PetName = Pet }))
                .Where(w => w.PetName.StartsWith("S"));

            DemoHelper.ShowData(Nested);
        }
    }

    public class PetOwner
    {
        public string Name { get; set; }
        public List<string> Pets { get; set; }
    }

    public class Result
    {
        public string PetOwner { get; set; }
        public string PetName { get; set; }

        public override string ToString()
        {
            return $"PetOwner:{PetOwner} - PetName:{PetName}";
        }
    }

    public static class DemoHelper
    {
        public static List<PetOwner> GetDate()
        {
            return new List<PetOwner>() {
                new PetOwner { Name="Higa",Pets = new List<string>{ "Scruffy", "Sam" } },
                new PetOwner { Name="Ashkenazi",Pets = new List<string>{ "Walker", "Sugar" } },
                new PetOwner { Name="Price",Pets = new List<string>{ "Scratches", "Diesel" } },
                new PetOwner { Name="Hines",Pets = new List<string>{ "Dusty" } } };
        }

        public static void ShowData(IEnumerable<Result> Data)
        {
            foreach (var item in Data)
            {
                Console.WriteLine(item);
            }
        }
    }
}
[LINQ] SelectMany-3

MSDN SelectMany 說明
SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>)
簡單的用兩張圖片來輔助說明,方便了解

[LINQ] SelectMany-1

[LINQ] SelectMany-2

沒有留言:

張貼留言