我有两个Requests
和Responses
列表,它们继承自抽象AbstractLineModel
类。响应和请求都包含名为DateTime
,MethodName
和GUID
的DateTime(或不包含)。
CallPair
包含一对匹配的Request
和Response
:
public class CallPair
{
public AbstractLineModel _request { get; set; }
public AbstractLineModel _response { get; set; }
public CallPair(AbstractLineModel request, AbstractLineModel response)
{
_request = request;
_response = response;
}
}
班级CallPairOrganizer
将调用组织到以下列表中:
public class CallPairOrganizer
{
// List of requests and matching responses
private List<CallPair> _callPairs = new List<CallPair>();
private List<AbstractLineModel> _lines = new List<AbstractLineModel>();
private List<AbstractLineModel> _requests = new List<AbstractLineModel>();
private List<AbstractLineModel> _responses = new List<AbstractLineModel>();
private List<AbstractLineModel> _unmatchedRequests = new List<AbstractLineModel>();
private List<AbstractLineModel> _unmatchedResponses = new List<AbstractLineModel>();
}
这是CallPairOrganizer
类的两种方法:(1)在早期answer的帮助下,我创建了List
CallPairs
Request
在GUID
中匹配与Response
相同的Callpair
:
public void MatchCallPairsByRequestId()
{
// Finds request that have matching response based on RequestId and create
// callpair
_callPairs = _requests.Distinct().Where(req => !string.IsNullOrEmpty
(req.RequestId))
.Join(_responses.Distinct(),
req => req.RequestId,
resp => resp.RequestId,
(req, resp) => new CallPair(req, resp)).ToList();
CollectUnmatchedCalls();
}
并且(2)我按如下方式收集所有不匹配的请求和响应:
public void CollectUnmatchedCalls()
{
_unmatchedRequests =
_requests.Except(_callPairs.Select(cp => cp._request)).ToList();
_unmatchedResponses = _responses.Except(_callPairs.Select(cp =>
cp._response)).ToList();
}
这很有效。下一步是比较不匹配的请求和响应,并根据DateTime属性对它们进行排序,如果它们是相同的MethodName
。如果请求和响应彼此最接近,我希望将它们匹配到CallPair
。
有了这部分,我很难弄清楚要使用什么算法/ linq。我希望有人可以根据日期时间向我提供有关如何完成将请求与同一MethodName
的响应相匹配的任务的见解。
答案 0 :(得分:1)
那么,你需要找到一个请求的“最接近的”响应吗?
//just some objects for me to play with
var requests = Enumerable.Range(1).Select(i => new { Time = DateTime.Now, Method = "blah" }).ToList();
var responses = Enumerable.Range(1).Select(i => new { Time = DateTime.Now, Method = "blah" }).ToList();
foreach (var req in requests)
{
//In all of the responses - find the one that happened soonest after the request (with the same method name)
var closestResponse = responses
.Where(resp => resp.Method == req.Method)
.OrderBy(resp => resp.Time - req.Time)
.FirstOrDefault();
//No more responses - exit
if(closestResponse == null)
break;
responses.Remove(closestResponse);
//make new call pair, with the closest rseponse
}