Given two IEnumberables of different types, what is the best practice (considering readability and maintainability) for iterating over both lists to perform an action on all possible combinations?
My initial solution was to use nested foreach loops, iterating over the first IEnumerable, and then within that loop, iterating over the second IEnumerable and passing the value from the outer and the current loop into the target method. Eg.:
enum ParamOne
{
First,
Second,
Etc
}
List<int> paramTwo = new List<int>() { 1, 2, 3 };
void LoopExample()
{
foreach (ParamOne alpha in Enum.GetValues(typeof(ParamOne)))
{
foreach (int beta in paramTwo)
{
DoSomething(alpha, beta);
}
}
}
I tried to restructure it with LINQ, but ended up with something that had no obvious advantages and seemed less intuitive. A search here shows lots of questions about nesting foreachs to iterate over child properties, but I couldn’t find anything about iterating over two distinct lists.
I don’t see anything particularly wrong with your solution. That being said, the simplest LINQ procedure would seem to be:
Given that it’s a little…obtuse…I would recommend sticking with the two
foreachoperations. That’s less expensive than all of the shenanigans that the C# compiler is going to go through in order to make that expression work (since we’re dealing both with closures and anonymous types).