嵌套的foreach循环转换为lambda或linq

时间:2016-10-11 08:06:58

标签: sql linq foreach lambda nested-loops

我正在努力将其转换为lambda但却无法成功。有没有方法可以转换为linq或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
        //{

        //}
    }
}

1 个答案:

答案 0 :(得分:0)

您可以对包含所有相关属性的匿名类型Join

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