2014-03-13 99 views
0

我有以下表現:如何將linq表達式與連接轉換爲lambda表達式?

_callPairs = (from req in _requests 
         join resp in _responses 
          on req.RequestId equals resp.RequestId 
          where !string.IsNullOrEmpty(req.RequestId) 
         select new CallPair(req, resp)).ToList(); 

,我想換拉姆達。我試過了:

_callPairs = _requests.Where(req => (_responses.Where(res => res.RequestId == 
    req.RequestId)).Where(!string.IsNullOrEmpty(req.RequestId)).ToList(); 

不幸的是,這不能編譯。

有人可以向我解釋我如何將linq表達式與連接轉換爲lambda表達式?

回答

3

只需使用Join()方法:

_callPairs = _requests.Where(req => !string.IsNullOrEmpty(req.RequestId)) 
         .Join(_responses, 
          req => req.RequestId, 
          resp => resp.RequestId, 
          (req, resp) => new CallPair(req, resp)).ToList(); 
2

這取決於連接的類型。這裏有一個內部聯接(可以缺少一個into條款的告知),所以相應的擴展方法的語法使用Join

_callPairs = _requests 
       .Where(req => !string.IsNullOrEmpty(req.RequestId)) 
       .Join(_responses,     // join to what? 
         req => req.RequestId,  // compare this from requests 
         resp => resp.RequestId,  // to this key from responses 
         (req, resp) => new CallPair(req, resp)) // create result 
       .ToList(); 

對於組加入(join ... on ... into ...)你會使用GroupJoin代替。