Search code examples
c#.netlinq

How do I update a list<> from another list<> with two conditions using linq?


How can I update the following approach using linq to update a loop within a loop, and having two conditions? I've looked at other posts that are similar but not with two conditions.

foreach (var pCalc in curPrefCalc)
{
    if (pCalc.IsVariable)
    {
        foreach (var pr in primeRt)
        {
            if (pCalc.prefbeg >= pr.BegDate && pCalc.prefend <= pr.EndDate)
            {
                pCalc.VariableRate = pr.Rate;
            }
            else if (pCalc.prefbeg >= pr.BegDate)
            {
                pCalc.VariableRate = pr.Rate;
            }
        }
    }
}

Solution

  • How about something like:

    curPrefCalc.Where(pCalc => pCalc.IsVariable)
        .ToList()
        .ForEach(pCalc =>
        {
            var matchingRate = primeRt
                .Where(pr => pCalc.prefbeg >= pr.BegDate && pCalc.prefend <= pr.EndDate || pCalc.prefbeg >= pr.BegDate)
                .Select(pr => pr.Rate)
                .FirstOrDefault();
    
            if (matchingRate != default)
            {
                pCalc.VariableRate = matchingRate;
            }
        });