使用LINQ to创建两个不同的列表,其中的条目具有相同的属性对 [英] Using LINQ to create pairs from two different list where the entries have same attribute

查看:112
本文介绍了使用LINQ to创建两个不同的列表,其中的条目具有相同的属性对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请求的两个列表响应谁从抽象继承 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作为响应 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
。凡(REQ => = req.RequestId))了ToList();
返回requestsWithMatches的空列表

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创建两个不同的列表,其中的条目具有相同的属性对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆