2014-03-29 85 views
0

我有兩個LINQ查詢如下:合併兩個查詢在LINQ

GroupNamesWithCorrespondingEffects 
     = new ObservableCollection<GroupNameWithCorrespondingEffect>(
            from g in db.Groups 
            select new GroupNameWithCorrespondingEffect 
               { 
                GroupID = g.GroupID, 
                GroupName = g.GroupName, 
                CorrespondingEffect = g.Master_Effects.Effect 

               } 
             ); 

GroupNamesWithCorrespondingEffects 
      = new ObservableCollection<GroupNameWithCorrespondingEffect>  
         (GroupNamesWithCorrespondingEffects. 
          Where(u => !GetAllChildren(25). 
             Select(x => x.GroupID). 
             Contains(u.GroupID)).ToList()); 

現在,我怎麼合併這兩個查詢?

回答

1

您可以直接在此傳遞給ObservableCollection的構造函數:

from g in groups 
let g = select new GroupNameWithCorrespondingEffect 
     { 
      GroupID = g.GroupID, 
      GroupName = g.GroupName, 
      CorrespondingEffect = g.Master_Effects.Effect 
     } 
where !GetAllChildren(25) 
     .Select(x => x.GroupID) 
     .Contains(g.GroupID) 
select g 

我不確定EF是否能夠編寫第一部分和第二部分(如果ContainsIN條款中解決,我的EF有點生疏),但是您不是無論如何,這樣做的效果和你一樣RS。如果能夠撰寫,那麼這樣你就可以獲得更高效的執行。

+0

我已經試過你的答案以及尼爾的其他答案。在這兩種情況下,我得到以下錯誤:'LINQ to Entities無法識別'System.Collections.Generic.IEnumerable'1 [WPF_Client.HelperClasses.GroupNameWithCorrespondingEffect] GetAllChildren(Int32)'方法,並且此方法無法翻譯' – Vishal

+0

好的,EF無法撰寫,因爲我懷疑。它應該像提取GetAllChildren(25)一樣簡單。在變量中選擇(x => x.GroupID).ToList()並使用該變量來執行Contains。如果那個引發同樣的問題,你可以拿Neil的答案,並在.Where調用之前添加一個ToList()。第二部分將在內存中運行,但它與您在代碼中所做的無關。 – Wasp

+0

感謝您解釋這一行:'第二部分將在內存中運行,但它與您在代碼中所做的沒有什麼不同。「同時感謝您的回答。 – Vishal

0

如果你不介意的混合SQL風格和擴展方法的語法,你可以這樣做:

GroupNamesWithCorrespondingEffects 
     = new ObservableCollection<GroupNameWithCorrespondingEffect>(
       (from g in groups 
       select new GroupNameWithCorrespondingEffect 
        { GroupID = g.GroupID, 
         GroupName = g.GroupName, 
         CorrespondingEffect = g.Master_Effects.Effect 
        }) 
       .Where(u => !GetAllChildren(25) 
         .Select(x => x.GroupID) 
         .Contains(u.GroupID)) 
       .ToList()); 
+0

我已經嘗試過您的答案以及來自Wsap的其他答案。在這兩種情況下,我得到以下錯誤:'LINQ to Entities does not recognized the method'System.Collections.Generic.IEnumerable'1 [WPF_Client.HelperClasses.GroupNameWithCorrespondingEffect] GetAllChildren(Int32)'method,and this method can not be' – Vishal