tags:

views:

168

answers:

4

What is the extension method equivalent of the following LINQ?

var qry = from a in context.A_Collections
          from b in context.B_Collections
          where a.PK == b.PK
          select 
        new {
              A_key = a.PK, 
              A_Value = a.Value,
              B_Key = b.PK,
              B_value = b.value
            };

I mean

(incomplete)

var query = context.A_Collections.
                Where(
                      a => a.PK == context.B_Collections.Select(b => b.PK)).
                    Select(
                            x => new { 
                                      A_key = a.Pk,
                                      A_Value = a.Value,
                                      B_Key = b.PK,
                                      B_value = b.value
                                     }
                           );
A: 

It would be something like:

context.A_Collections.Include("B")
.Where(a => a.PK == a.B.PK)
.Select(a => 
     new {A_key = a.PK, 
          A_Value = a.Value, 
          B_Key = a.B.PK, 
          b_value = a.B.value } );
klausbyskov
A: 

Try using Resharper this will help you to convert all Linq queris in Linq Methods if you prefer that.

Florim Maxhuni
+2  A: 

It looks like you're trying to do a join, so it would be:

var query = context.A_Collections.Join(
 context.B_Collections,
 a => a.PK,
 b => b.PK,
 (a, b) => new {
  A_key = a.PK,
  A_value = a.Value,
  B_Key = b.PK,
  B_value = b.value
 });

EDIT: As Jon Skeet points out however, the actual translation done by the compiler will use SelectMany although using group will probably be more efficient.

Lee
+5  A: 

Subsequent "from" clauses translate to SelectMany calls:

var qry = context.A_Collections
                 .SelectMany(a => context.B_Collections,
                             (a, b) => new { a, b })
                 .Where(x => x.a.PK == x.b.PK)
                 .Select(x => new { A_key = x.a.PK,
                                    A_value = x.a.Value,
                                    B_key = x.b.PK,
                                    B_value = x.b.Value });

The "x" bit is due to the introduction of a transparent identifier.

Note that a call to Join may be more efficient than using SelectMany (depending on the exact situation), but this is the more direct translation of the query you started with.

Jon Skeet