Search code examples
sqllinqforeachlambdanested-loops

Nested foreach loop conversion to lambda or linq


I am trying much to convert it to lambda but could not succeed. Is there any method to convert to linq or lambda?

foreach (var tempitem in mbsRateTempList)
{
    foreach (var Saveditem in mbsSavedRecordList)
    {
        if (tempitem.MbsSecurityId == Saveditem.MbsSecurityId && tempitem.CouponRate == Saveditem.CouponRate
               && tempitem.SettlementMonth.Month == Saveditem.SettlementMonth.Month && tempitem.Price == Saveditem.Price)
        {
            TobeDeletedIds.Add(Saveditem.Id);
            MatchedIdsInTempList.Add(tempitem.TempId);
            //mbsSavedRecordList[0].ObjectState=Repository.Pattern.Base.Infrastructure.ObjectState.
        }
        //else
        //{

        //}
    }
}

Solution

  • You can Join on anonymous types containing all relevant properties:

    var objectsToAdd = from tempitem in mbsRateTempList
                       join saveditem mbsSavedRecordList
                       on new { tempitem.MbsSecurityId,  tempitem.CouponRate, tempitem.SettlementMonth.Month, tempitem.Price } 
                       equals new { saveditem.MbsSecurityId,  saveditem.CouponRate, saveditem.SettlementMonth.Month, saveditem.Price } 
                       select new { tempitem, saveditem };
    
    foreach(var x in objectsToAdd)
    {
        TobeDeletedIds.Add(x.saveditem.Id);
        MatchedIdsInTempList.Add(x.tempitem.TempId);
    }