Often with lists and the items inside them, I find the need to query or find things in the list the object has been added to.
For example:
// create list of levels
IList<Levels> levels = new List<Levels>
{
levels.Add(new Level{ Depth = 1, Name = "Level 1" });
levels.Add(new Level{ Depth = 2, Name = "Level 2" });
}
foreach(Level level in levels)
{
bool lowestLevel = false;
// would the lowest level be best worked out from a function that takes the list and the level?
lowestLevel = Level.GetLowest(Levels, level);
// as a calculated property of level itself where the level knows about the list of levels it's in?
lowestLevel = Level.IsLowest;
// or worked out when creating the level?
// levels.Add(new Level{ Depth = 1, Name = "Level 1", IsLowest = isLowest });
lowestLevel = Level.IsLowest;
}
Are any of these a ‘best practice’ way to handle something like this or is there another way?
Thanks in advance.
Ignoring the fact that adding to the collection being iterated over throws an exception…
There is definitely another way. When a
Levelneeds to know about its siblings, you should encapsulatelevelsinside a class, sayLevelCollection. You can give eachLevela reference to its parent collection when you insert a level into a collection, and stop passinglevelsin the methods than need the siblings.