views:

91

answers:

2

I can't seem to figure out the LINQ Join extension method... I have the following LINQ inline query:

var cc = from z in zipcodes
         join c in contactsRepo.UDF_SelectSome() on z.Zipcode equals c.Zip       

What is the equivalent of this in LINQ-extension-method syntax?

+4  A: 

Did you mean Lambda syntax?

var cc = zipcodes.Join(contactsRepo.UDF_SelectSome(),
                       z => z.Zipcode,
                       c => c.Zip,
                       (z, c) => c);
Justin Niessner
If I want the (z, c) => new to be of type contactsRepoResults, do I still need to cast it, or can I just do something like new contactsRepoResults() ? Because essentially I'm using the join only as a filter, I still want the same stuff returned that would usually be returned by contactsRepo.UDF_SelectSome().
Alex
@Alex - I updated to reflect that. Keep in mind, though, that your original post won't give you those results. It will return a new anonymous type with the combined fields of the two tables unless you specify a select clause.
Justin Niessner
@Justin: I shortened my original post because my main issue was the join. In your update, you show FieldOne = z.FieldOne etc. - is it possible to automagically assign it a type without casting each field? Because my type has 30+ fields, and I really don't need any field from the zipcode table, so it's the same fields that would ordinarily be returned by the UDF (and then casted correctly)
Alex
Alternatively, can I have the join return an IQueryable?
Alex
A: 

If you're using the join to filter, and you want just the object from one set, use the selector (last parameter) that picks that object.

var cc = contactsRepo.UDF_SelectSome().Join(
  zipcodes,
  c => c.Zip,
  z => z.Zipcode,
  (c, z) => c); 

Or, if you just want to filter:

var cc = contactsRepo.UDF_SelectSome()
  .Where(c => zipcodes.Any(z => c.Zip == z.ZipCode))
David B
The (c, z) => c was exactly what I was looking for.
Alex