I have two IEnumerable
s:
IEnumerable<string> first = ...
IEnumerable<string> second = ...
I want to create a second IEnumerable<string>
that is the concatenation of each element of each IEnumerable
.
For example:
IEnumerable<string> first = new [] {"a", "b"};
IEnumerable<string> second = new [] {"c", "d"};
foreach (string one in first)
{
foreach (string two in second)
{
yield return string.Format("{0} {1}", one, two);
}
}
This would produce:
"a c"; "a d"; "b c"; "b d";
The problem is, sometimes one of the two IEnumerable
s is empty:
IEnumerable<string> first = new string[0];
IEnumerable<string> second = new [] {"c", "d"};
In this case, the nested foreach
construct never reaches the yield return
statement. When either IEnumerable
is empty, I would like the result to just be the list of the non-empty IEnumerable
.
How can I produce the combinations I am looking for?
EDIT:
In reality, I have three different IEnumerable
s I am trying to combine, so adding if conditions for every possible permutation of empty IEnumerable
seems bad. If that's the only way, then I guess I'll have to do it that way.