Is is possible to convert following into a simpler more readable linq or lambda expression?
Dictionary<int, int> selectedProgramTierCombo = new Dictionary<int,int>();
foreach (int mainTierID in doc.TierID)
{
foreach (PriceProgram priceProgram in doc.CommitmentProgram.PricingPrograms)
{
foreach (ProgramTier progTier in priceProgram.Tiers)
{
if (progTier.TierID == mainTierID )
{
selectedProgramTierCombo.Add(priceProgram.ProgramID, progTier.TierID);
}
}
}
}
Essentially doc.TierID is a an array (int[]) of TierIDs that client is currently on. Also the doc object contains a CommitmentProgram object which contains a list of PriceProgram. So, All I am trying to do is get the PriceProgram.ProgramID for each TierID.
The relationship between PriceProgram and TierID is that each PriceProgram has a list of tiers (ProgramTier object) and ProgramTier oject contains the corresponding TierID that we already have.
Let me know if my explaination doesn’t make sense and I’ll try to elaborate.
Edit
Jon,
I am getting The name ‘priceProgram’ does not exist in the current context error when I try to compile what you have suggested:
Dictionary<int, int> selectedProgramTierCombo =
(from mainTierID in doc.TierID
from priceProgram in doc.CommitmentProgram.PricingPrograms
**join progTier in priceProgram.Tiers on mainTierID equals progTier.TierID**
select new { priceProgram.ProgramID, progTier.TierID })
.ToDictionary(x => x.ProgramID, x => x.TierID);
Absolutely, it’s very easy – but I’ll have to change the type of your
selectedProgramTierCombovariable, as otherwise it won’t compile:EDIT: Oops, given that the tiers depends on priceProgram, you need another nested
fromclause, I think:At least, that’s what I think you want. If you could clarify what you really want instead of
List<int, int>(which isn’t valid) we can help further.To be honest, it’s not clear to me why you’re using
progTierat all – you know thatprogTier.TierIDis the same asmainTierID, and you’re not using it apart from that…