[英]How to convert linq expression with join to lambda expression?
我有以下表达:
_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();
我想更改为lambda。 我试过了:
_callPairs = _requests.Where(req => (_responses.Where(res => res.RequestId ==
req.RequestId)).Where(!string.IsNullOrEmpty(req.RequestId)).ToList();
不幸的是,这无法编译。
有人可以向我解释如何将带有联接的linq表达式转换为lambda吗?
只需使用Join()
方法:
_callPairs = _requests.Where(req => !string.IsNullOrEmpty(req.RequestId))
.Join(_responses,
req => req.RequestId,
resp => resp.RequestId,
(req, resp) => new CallPair(req, resp)).ToList();
这取决于联接的类型。 在这里,您有一个内部Join
(可以通过缺少一个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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.