Using LINQ to create pairs from two different lists in which records have the same attribute

I have two lists Requestsand Responsesthat inherit from an abstract class AbstractLineModel. Both responses and requests contain an identifier (or not) with a name RequestId.

A CallPaircontains the matching pair Requestand a Responseand has the following constructor:

public AbstractLineModel _request { get; set; }
public AbstractLineModel _response { get; set; }

public CallPair(AbstractLineModel request, AbstractLineModel response)
{
    _request = request;
    _response = response;
}

I want to do List CallPairswhere Requestwith the same identifier as, it Responsemaps to CallPair. How to match the list Requestsand Responses?

What I tried:

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));
    }
}

but this returns an empty list.

In particular, it var requestWithMatches = _requests .Where(req => _responses.All(res => res.RequestId == req.RequestId)).ToList();returns an empty list of requestsWithMatches.

Can someone help me with this algorithm?

+4
2

RequestId CallPair :

 var requestWithMatches = from req in _requests
                          join resp in _responses
                             on req.RequestId equals resp.RequestId
                          select new CallPair(req, resp);
+4

Enumerable.Join :

public void MatchCallPairs()
{
    // Finds request that have matching response
    var requestWithMatches = from req in _requests
                             join resp in _responses
                             on req.RequestId equals resp.RequestId
                             select new CallPair(req, resp);
    _callPairs =  requestWithMatches.ToList();
}

, , :

_responses.All(res => res.RequestId == req.RequestId)

, All 'RequestId.

+2

Source: https://habr.com/ru/post/1528991/


All Articles