Difference Between Select and SelectMany

后端 未结 17 1284
长情又很酷
长情又很酷 2020-11-22 05:21

I\'ve been searching the difference between Select and SelectMany but I haven\'t been able to find a suitable answer. I need to learn the differenc

17条回答
  •  花落未央
    2020-11-22 05:29

    Select many is like cross join operation in SQL where it takes the cross product.
    For example if we have

    Set A={a,b,c}
    Set B={x,y}
    

    Select many can be used to get the following set

    { (x,a) , (x,b) , (x,c) , (y,a) , (y,b) , (y,c) }
    

    Note that here we take the all the possible combinations that can be made from the elements of set A and set B.

    Here is a LINQ example you can try

    List animals = new List() { "cat", "dog", "donkey" };
    List number = new List() { 10, 20 };
    
    var mix = number.SelectMany(num => animals, (n, a) => new { n, a });
    

    the mix will have following elements in flat structure like

    {(10,cat), (10,dog), (10,donkey), (20,cat), (20,dog), (20,donkey)}
    

提交回复
热议问题