Suppose there's the following set up (assume equal lengths and general niceness of the data).
List<String>
a = GetStrings(0),
b = GetStrings(1);
for(int i = 0; i < a.Count; i++)
yield return new SuperString{ A = a[i], B = b[i] };
What I wonder is if this can be refactored into a foreach loop and if it'd look very ugly then. I prefer using it before for since the operation will be performed on each of the element pair.
EDIT:
I might have been to scarce on the details. Sorry about that. What if the types are arbitrary? I.e. as the following?
IEnumerable<Cool> a = GetCool();
IEnumerable<Lame> b = GetLame();
for(int i = 0; i < a.Count; i++)
yield return new Opposites{ A = a[i], B = b[i] };
How about no loop at all?
a.Zip(b, (aa, bb) => new SuperString{A = aa, B = bb})
the benefit of the Zip method is that it will stop at the end of the shorter of the two sequences in the case they're of differing lengths.
Note: if you're using .net < 4, you'll want to take @Cuong's method.
In the case that your types are arbitrary, exactly the same should work:
IEnumerable<Cool> a = GetCool();
IEnumerable<Lame> b = GetLame();
a.Zip(b, (aa, bb) => new Opposites{A = aa, B = bb});
with the caveat that property A of Opposites must be of type Cool and B of type Lame (or a parent type)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With