2012-02-08 108 views
1

我想這個LINQ代碼切換到lambda表達式:如何LINQ查詢使用拉姆達表達式轉換

foreach (var id in orderLinesToSplit) 
{ 
    int result = 
     (from ol in orderLines 
     from splittedOl in orderLines 
     where ol.Key == id 
      && ol.Value == splittedOl.Value 
      && ol.Key != splittedOl.Key 
     select splittedOl.Key).FirstOrDefault(); 
} 

的目標是獲得一個對id(從oderLinesToSplit)和resultDictionary<int, int> (來自linq查詢的結果)。它可以用一個lambda表達式來完成嗎?

感謝

回答

1
var result= 
(
    from ol in orderLines 
    from splittedOl in orderLines 
    where orderLinesToSplit.Contains(ol.Key) 
     && ol.Value == splittedOl.Value 
     && ol.Key != splittedOl.Key 
     select new 
     { 
     splittedOl.Key, 
     splittedOl.Value 
     } 
    ).ToDictionary (v =>v.Key,v=>v.Value); 

或者,如果你真的想在一個表達。然後是這樣的:

var result= 
    (
     db.orderLines.Join 
      (
       db.splittedOl, 
       ol=>ol.Value, 
       splittedOl=>splittedOl.Value, 
       (ol,splittedOl)=>new 
       { 
        olKey=ol.Key, 
        splittedOlKey=splittedOl.Key 
       } 
      ).Where(l =>l.olKey!= l.splittedOlKey && orderLinesToSplit.Contains(l.olKey)) 
      .ToDictionary(l =>l.olKey,v=>v.splittedOlKey) 
    ); 

其中db是LINQ數據上下文

+0

耶的作品,但我需要的拉姆達expresion ...... – 2012-02-08 13:16:45

+0

更新答案 – Arion 2012-02-08 14:22:15

+0

@LauraJimenez爲什麼你需要它作爲一個拉姆達表達?它的查詢相同,只是難以閱讀。 – Magnus 2012-02-08 17:21:42