• C# Linq中的Select和SelectMany


    C#中Linq的select 语句很好理解,因为这个select类似于sql语句中的select——筛选出感兴趣的字段,但是SelectMany就不好理解了,本文主要讲解一下SelectMany,顺便和Select对比。

     

    目录

    1.SelectMany的官方定义

     2.例子

    3. Select和SelectMany的对比

    4.SelectMany的扩展



    1.SelectMany的官方定义

            官方定义很简单,就是一句话:将一个序列中的每个元素映射成一个可枚举对象,然后将这些对象合并到一个序列中。

     看完可能还是有点懵逼,我们再看看函数定义:

    函数定义有点复杂,如果你能看懂,那就不用看下文了。如果觉得理解有点困难就看下面的例子:

     2.例子

    先看官方的例子:

    1. class PetOwner
    2. {
    3. public string Name { get; set; }
    4. public List<string> Pets { get; set; }
    5. }
    6. public static void SelectManyEx3()
    7. {
    8. PetOwner[] petOwners =
    9. { new PetOwner { Name="Higa",
    10. Pets = new List<string>{ "Scruffy", "Sam" } },
    11. new PetOwner { Name="Ashkenazi",
    12. Pets = new List<string>{ "Walker", "Sugar" } },
    13. new PetOwner { Name="Price",
    14. Pets = new List<string>{ "Scratches", "Diesel" } },
    15. new PetOwner { Name="Hines",
    16. Pets = new List<string>{ "Dusty" } } };
    17. // Project the pet owner's name and the pet's name.
    18. var query =
    19. petOwners
    20. .SelectMany(petOwner => petOwner.Pets, (petOwner, petName) => new { petOwner, petName })
    21. .Where(ownerAndPet => ownerAndPet.petName.StartsWith("S"))
    22. .Select(ownerAndPet =>
    23. new
    24. {
    25. Owner = ownerAndPet.petOwner.Name,
    26. Pet = ownerAndPet.petName
    27. }
    28. );
    29. // Print the results.
    30. foreach (var obj in query)
    31. {
    32. Console.WriteLine(obj);
    33. }
    34. }
    35. // This code produces the following output:
    36. //
    37. // {Owner=Higa, Pet=Scruffy}
    38. // {Owner=Higa, Pet=Sam}
    39. // {Owner=Ashkenazi, Pet=Sugar}
    40. // {Owner=Price, Pet=Scratches}

    这里调用的是这个函数:

    public static System.Collections.Generic.IEnumerable<TResult> SelectMany<TSource,TCollection,TResult> (this System.Collections.Generic.IEnumerable source, Func> collectionSelector, Func resultSelector);

    注意第一个参数:

    Func> collectionSelector

    传入的是一个func,func的入参为原集合的元素,对应起来就是PetOwner,返回的是Pets成员,也就是集合,从名字上来说就是指定要flatten的集合,简而言之就是给我把Owner的Pets全部撸到一个集合里面去。

    第二个参数:

    Func resultSelector

    就是一个选择器,从TSource和TCollection中选择,构成TResult。

    如果只是想获取所有的pets信息;可以用另一个版本:

    public static System.Collections.Generic.IEnumerable<TResult> SelectMany<TSource,TResult> (this System.Collections.Generic.IEnumerable source, Func> selector);
    1. // Query using SelectMany().
    2. IEnumerable<string> query1 = petOwners.SelectMany(petOwner => petOwner.Pets);
    3. Console.WriteLine("Using SelectMany():");
    4. // Only one foreach loop is required to iterate
    5. // through the results since it is a
    6. // one-dimensional collection.
    7. foreach (string pet in query1)
    8. {
    9. Console.WriteLine(pet);
    10. }

    3. Select和SelectMany的对比

    看下面的例子:

    1. public class PhoneNumber
    2. {
    3. public string Number { get; set; }
    4. }
    5. public class Person
    6. {
    7. public IEnumerable PhoneNumbers { get; set; }
    8. public string Name { get; set; }
    9. }
    10. IEnumerable people = new List();
    11. // Select gets a list of lists of phone numbers
    12. IEnumerable> phoneLists = people.Select(p => p.PhoneNumbers);
    13. // SelectMany flattens it to just a list of phone numbers.
    14. IEnumerable phoneNumbers = people.SelectMany(p => p.PhoneNumbers);

    这个例子简单明了:用Select得到的是List>结构,而SelectMany得到的是List<>,所以官方定义会中有flatten这个词。

    所以前面的例子用Select代替就可以写为:

    1. // This code shows how to use Select()
    2. // instead of SelectMany().
    3. IEnumerable> query2 =
    4. petOwners.Select(petOwner => petOwner.Pets);
    5. Console.WriteLine("\nUsing Select():");
    6. // Notice that two foreach loops are required to
    7. // iterate through the results
    8. // because the query returns a collection of arrays.
    9. foreach (List petList in query2)
    10. {
    11. foreach (string pet in petList)
    12. {
    13. Console.WriteLine(pet);
    14. }
    15. Console.WriteLine();
    16. }

    4.SelectMany的扩展

            官方还提供了一个能获取索引的版本:

    public static System.Collections.Generic.IEnumerable<TResult> SelectMany<TSource,TResult> (this System.Collections.Generic.IEnumerable source, Funcint,System.Collections.Generic.IEnumerable> selector);

    也就是比上一个版本对一个Int类型参数! 

    1. class PetOwner
    2. {
    3. public string Name { get; set; }
    4. public List<string> Pets { get; set; }
    5. }
    6. public static void SelectManyEx2()
    7. {
    8. PetOwner[] petOwners =
    9. { new PetOwner { Name="Higa, Sidney",
    10. Pets = new List<string>{ "Scruffy", "Sam" } },
    11. new PetOwner { Name="Ashkenazi, Ronen",
    12. Pets = new List<string>{ "Walker", "Sugar" } },
    13. new PetOwner { Name="Price, Vernette",
    14. Pets = new List<string>{ "Scratches", "Diesel" } },
    15. new PetOwner { Name="Hines, Patrick",
    16. Pets = new List<string>{ "Dusty" } } };
    17. // Project the items in the array by appending the index
    18. // of each PetOwner to each pet's name in that petOwner's
    19. // array of pets.
    20. IEnumerable<string> query =
    21. petOwners.SelectMany((petOwner, index) =>
    22. petOwner.Pets.Select(pet => index + pet));
    23. foreach (string pet in query)
    24. {
    25. Console.WriteLine(pet);
    26. }
    27. }
    28. // This code produces the following output:
    29. //
    30. // 0Scruffy
    31. // 0Sam
    32. // 1Walker
    33. // 1Sugar
    34. // 2Scratches
    35. // 2Diesel
    36. // 3Dusty

    注意,SelectMany所要选择的集合不一定是原对象中的集合:

    1. List<string> animals = new List<string>() { "cat", "dog", "donkey" };
    2. List<int> number = new List<int>() { 10, 20 };
    3. var mix = number.SelectMany(num => animals, (n, a) => new { n, a });
    4. foreach(var x in mix)
    5. {
    6. Console.WriteLine(x.n+"=="+x.a);
    7. }

    这样可以很方便的生成笛卡尔积形式结果:

    1. 10==cat
    2. 10==dog
    3. 10==donkey
    4. 20==cat
    5. 20==dog
    6. 20==donkey

  • 相关阅读:
    蛋白结构合理性评估软件-PROCHECK的安装与使用
    beego框架自学笔记1
    索尼3D环境感知研究解析,目标是让所有设备“理解世界”
    基于模三干扰分析的终端优化设计
    【影刀演示_发送邮件的格式化HTML留存】
    山东省如何准备申报“专精特新”?
    spring aop
    【版本控制工具一】Git 安装注册及使用
    用 Canvas 画简易手电筒
    A股风格因子看板 (2023.11 第11期)
  • 原文地址:https://blog.csdn.net/q__y__L/article/details/125993474