Nested foreach loops is something that I have always felt uncomfortable with. Recently I have found out more elegant and in some cases even more efficient, replacement for nested double foreach loop.Lets assume we have two lists of strings filled with some values
and we want to have a collection of all combinations of elements from list l1with elements from list l2.
Obvious solution comes naturally as nested double foreach loop
And here comes the replacement, I mentioned about, which is based on Join extension method.
The definition of Join method says that it correlates elements of two sequences based on matching keys. Since here we want to correlate each element with each element we fake the element’s key selector by returning true as a key for every element from both sequences.
Quick performance tests showed that in some cases foreach loop approach is faster, in other cases Join approach is faster, but there is one big advantage of using Join approach over foreach loop. In a test where each list has 10 thousand of integer numbers, the foreach loop approach crashes with OutOfMemory exception while the Join approach finishes in about 5 seconds. This is 10^8 iterations and apparently foreach loop allocates memory less efficiently than the Join method.
For the convenience the Combine extension method which uses the Join approach to combine elements from two collections