2009-12-13 54 views
0

什麼是以下LINQ的等效擴展方法?C#-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 
      }; 

我的意思是

(不完全)

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 
            } 
          ); 

回答

5

隨後的「從」條款翻譯成SelectMany呼叫:

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 }); 

的「X」位是由於引入一個透明標識符的。

請注意,撥打Join可能比使用SelectMany(取決於具體情況)更有效,但這是您開始查詢的更直接翻譯。

0

這將是這樣的:

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 }); 
0

嘗試使用ReSharper的,這將幫助你所有的LINQ查詢轉換中的LINQ方法,如果你喜歡這一點。

2

它看起來就像你試圖做一個連接,所以這將是:

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 
}); 

編輯:由於喬恩斯基特然而指出,由編譯器完成實際的翻譯將使用雖然的SelectMany使用組可能會更有效率。