Moving between LINQ formats

Does anyone know how to write this

var q = from c in customers
        join o in orders on c.Key equals o.Key
        select new {c.Name, o.OrderNumber};

      

In this syntactic style?

var 1= customers.
    .join(???)
    .select(???)

      

I've been looking for a way to do this for a long time now, and now good luck. Everyone prefers the first syntax for textbooks, but I find the second much easier to determine the order of work when reading.

+2


source to share


3 answers


The compiler conversion process involves using a "transparent identifier" that makes the current customer and order available to the Select method. You can emulate this by making your own:

customers.Join(orders, c => c.Key, o => o.Key, (c, o) => new { c, o })
         .Select(x => new { x.c.Name, x.o.OrderNumber });

      



Instead, you can simply move your version of Name / OrderNumber to the Join call:

customers.Join(orders, c => c.Key, o => o.Key, (c, o) => new { c.Name, o.OrderNumber });

      

+3


source


This only requires one call to Enumerable.Join :



var q = customers.Join(
                orders, 
                c => c.Key, 
                o => o.Key, 
                (c, o) => new {c.Name, o.OrderNumber}
             );

      

+2


source


You can also check out LinqPad . It has a little lambda button for the bottom half of the screen and it translates the linq request to the chaining methods:

from p in PropertyListings
from rl in p.ResidentialListings 
select new {p.YearBuilt,p.ListingUrl}

      

translated into:

PropertyListings
.SelectMany (
  p => p.ResidentialListings, 
  (p, rl) => 
     new  
     {
        YearBuilt = p.YearBuilt, 
        ListingUrl = p.ListingUrl
     }
)

      

+2


source







All Articles