I am stuck with this horrible object model coming back from a 3rd party product. It's six levels of objects deep, and I have to loop through the collection in each level, to get the values I need, in order to produce a small object model that I actually require.
The code ends up looking like this (with variable and type names changed). How can I clean up this mess when I can't modify the structure of the rootObject
?
(This is .NET 3.5.)
var levelOneEnumerator = rootObject.GetEnumerator();
while (levelOneEnumerator.MoveNext())
{
var levelOneItem = levelOneEnumerator.Current as Foo_LevelOneItem;
if (levelOneItem == null) continue;
var levelTwoItemsEnumerator = levelOneItem.LevelTwoItems.GetEnumerator();
while (levelTwoItemsEnumerator.MoveNext())
{
var LevelTwoItemsItem = levelTwoItemsEnumerator.Current as Foo_LevelTwoItem;
if (LevelTwoItemsItem == null) continue;
var foobars = new List<FooBar>();
var levelThreeItemsEnumerator = LevelTwoItemsItem.LevelThreeItems.GetEnumerator();
while (levelThreeItemsEnumerator.MoveNext())
{
var levelThreeItem = levelThreeItemsEnumerator.Current as Foo_LevelThreeItem;
if (levelThreeItem == null) continue;
var levelFourItemsEnumerator = levelThreeItem.LevelFourItems.GetEnumerator();
while (levelFourItemsEnumerator.MoveNext())
{
var levelFourItem = levelFourItemsEnumerator.Current as Foo_LevelFourItem;
if (levelFourItem == null) continue;
var levelFiveItemsEnumerator = levelFourItem.LevelFiveItems.GetEnumerator();
while (levelFiveItemsEnumerator.MoveNext())
{
var levelFiveItem = levelFiveItemsEnumerator.Current as Foo_LevelFiveItem;
if (levelFiveItem == null) continue;
var levelSixItemsEnumerator = levelFiveItem.LevelSixItems.GetEnumerator();
while (levelSixItemsEnumerator.MoveNext())
{
var levelSixItem = levelSixItemsEnumerator.Current as Foo_LevelSixItem;
if (levelSixItem == null) continue;
var levelSixKey = levelSixItem.Key;
var foobar = foobars.Where(x => x.Key == levelSixKey).FirstOrDefault();
if (foobar == null)
{
foobar = new FooBar
{
LevelSixKey = levelSixKey,
TransDate = levelFiveItem.TransDate,
PaidAmount = 0
};
foobars.Add(foobar);
}
// * -1 because value should be positive, while product reports a negative (and vice versa)
foobar.PaidAmount += (levelFiveItem.PaidAmount ?? 0) * -1;
}
}
}
}
yield return new FooBarsCollection
{
Prop1 = levelTwoItemsItem.Prop1,
Prop2 = levelTwoItemsItem.Prop2,
Prop3 = levelTwoItemsItem.Prop3,
FooBars = foobars
};
}
}
IEnumerable<T>
? \$\endgroup\$foreach ()
loops, which is slightly better. But it's still the nesting that's driving me nuts, it just looks bad. \$\endgroup\$