问题描述
我请求的两个列表
和响应
谁从抽象继承 AbstractLineModel
类。无论是响应和请求中包含一个ID(或不)命名为的requestId
。
I have two lists of Requests
and Responses
who inherit from the abstract AbstractLineModel
class. Both the responses and requests contain an ID (or not) named RequestId
.
A CallPair
包含匹配对请求
和的响应
并具有以下构造:
A CallPair
contains a matching pair of Request
and a Response
and has the following constructor:
public AbstractLineModel _request { get; set; }
public AbstractLineModel _response { get; set; }
public CallPair(AbstractLineModel request, AbstractLineModel response)
{
_request = request;
_response = response;
}
我想打一个列表
CallPairs
其中请求
用相同的ID作为响应$的C $ C>在
Callpair
匹配。如何匹配采购清单
和响应
?
I want to make a List
of CallPairs
where the Request
with the same Id as the Response
are matched in the Callpair
. How to match the list of Requests
and Responses
?
我试过是:
public void MatchCallPairs()
{
// Finds request that have matching response
var requestWithMatches = _requests
.Where(req => _responses.All(res => res.RequestId == req.RequestId)).ToList();
// Match the request to the response
foreach (var req in requestWithMatches)
{
var resp = _responses.Where(res => res.RequestId == req.RequestId).FirstOrDefault();
// And create the pairs
_callPairs.Add(new CallPair(req, resp));
}
}
但这返回一个空列表。 _responses.All(RES => res.RequestId =
but this returns an empty list.
具体而言, VAR requestWithMatches = _requests
返回requestsWithMatches的空列表
。凡(REQ => = req.RequestId))了ToList();
Specifically, var requestWithMatches = _requests .Where(req => _responses.All(res => res.RequestId == req.RequestId)).ToList();
returns an empty list of requestsWithMatches.
有人可以帮我这个算法?
Can someone help me out with this algorithm?
推荐答案
刚加入的请求ID两个序列和加盟项目创建CallPair:
Just join both sequences on RequestId and create CallPair from joined items:
var requestWithMatches = from req in _requests
join resp in _responses
on req.RequestId equals resp.RequestId
select new CallPair(req, resp);
这篇关于使用LINQ to创建两个不同的列表,其中的条目具有相同的属性对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!