2014-03-13 67 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代替。