Difference Between Select and SelectMany

后端 未结 17 1083
长情又很酷
长情又很酷 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:41

    enter image description here

    var players = db.SoccerTeams.Where(c => c.Country == "Spain")
                                .SelectMany(c => c.players);
    
    foreach(var player in players)
    {
        Console.WriteLine(player.LastName);
    }
    
    1. De Gea
    2. Alba
    3. Costa
    4. Villa
    5. Busquets

    ...

    0 讨论(0)
  • 2020-11-22 05:42

    Select is a simple one-to-one projection from source element to a result element. Select- Many is used when there are multiple from clauses in a query expression: each element in the original sequence is used to generate a new sequence.

    0 讨论(0)
  • 2020-11-22 05:44

    Without getting too technical - database with many Organizations, each with many Users:-

    var orgId = "123456789";
    
    var userList1 = db.Organizations
                       .Where(a => a.OrganizationId == orgId)
                       .SelectMany(a => a.Users)
                       .ToList();
    
    var userList2 = db.Users
                       .Where(a => a.OrganizationId == orgId)
                       .ToList();
    

    both return the same ApplicationUser list for the selected Organization.

    The first "projects" from Organization to Users, the second queries the Users table directly.

    0 讨论(0)
  • 2020-11-22 05:46

    I understand SelectMany to work like a join shortcut.

    So you can:

    var orders = customers
                 .Where(c => c.CustomerName == "Acme")
                 .SelectMany(c => c.Orders);
    
    0 讨论(0)
  • 2020-11-22 05:48

    SelectMany() lets you collapse a multidimensional sequence in a way that would otherwise require a second Select() or loop.

    More details at this blog post.

    0 讨论(0)
提交回复
热议问题