Listing all combinations of lists of different types
Given two IEnumberables of different types, what is the best practice (considering readability and maintainability) for iterating over both lists to perform the action in all possible combinations?
My initial solution was to use nested foreach loops, iterate over the first IEnumerable, and then inside that loop, iterate over the second IEnumerable and pass the value from the outer and current loops to the target method. For instance:.
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 rebuilding it with LINQ, but ended up with something that had no obvious benefits and felt less intuitive. A search here reveals many questions about nesting foreachs to iterate over child properties, but I couldn't find anything about iterating over two separate lists.
a source to share
I don't see anything special in your solution. In this case, the simplest LINQ procedure will look like this:
foreach(var entry in enumerable1.SelectMany(
e => enumerable2.Select(e2 => new { First = e, Second = e2 })))
{
DoSomething(entry.First, entry.Second);
}
Considering this is a bit ... dumb ... I would recommend sticking with two operations foreach
. It's cheaper than all the tricks the C # compiler is going to go through to get this expression to work (since we're dealing with closures and anonymous types).
a source to share
As long as there is no overlap in the combinations, I don't see a more computationally efficient way to compute a function on the Cartesian product of two sets. However, if one of the lists has duplicate items, or the order of the arguments to DoSomething does not matter, and the lists have overlap, you will be handling redundant calls to DoSomething. You can save computation time by keeping Memoizing DoSomething.
a source to share