c# array collater where the output has the same value every other element

This is an extension of something I'm really working on. It is easy enough to do in a loop but I was wondering if I could find a single-code line.

This is the input:

byte[] x = new byte[] { (byte)'a', (byte)'b', (byte)'c', (byte)'d' };

Re-write the values anyway that you like but you get the point. you have to start with an array of bytes and end up with a collated array of bytes.

Here is the desired output:

byte[] { (byte)'a', (byte)'z', (byte)'b', (byte)'z', (byte)'c', (byte)'z', (byte)'d', (byte)'z'};

I tried variations of this but started with what I'm showing and knowing this would not work in itself.

var y = x.Select(c => new byte[] { c, (byte)'z' });

At the end of the day since these are only bytes is doesn't matter what the values are. Just that you can correlate some given value, 'z' in this case. And in as few lines, preferred a one-line, that is reasonably clear and concise.

Jon Skeet
people
quotationmark

You were very nearly there - you just need to use SelectMany instead of Select, as for each input element you're creating a sequence of output elements... then you want to flatten that "sequence of sequences" into a single sequence. That's precisely what SelectMany does.

So:

var y = x.SelectMany(c => new[] { c, (byte)'z' }).ToArray();

people

See more on this question at Stackoverflow