Is there an inverse/complement of IEnumerable.SelectMany? That is, is there a method of the form IEnumerable<T>.InverseSelectMany(Func<IEnumerable<T>,T>) which will find a sequence in the input sequence and perform a transform to a single element and then flatten the whole thing out again?
For example, if you wanted to replace all escape sequences { 0x7E, 0x7E } in an HDLC frame with just a single byte 0x7E, you could do something like
byte[] byteArray = new byte[] { 0x01, 0x02, 0x7E, 0x7E, 0x04 }; // etc.
byte[] escapeSequence = new byte[] { 0x7E, 0x7E };
byte[] outputBytes = byteArray.InverseSelectMany<byte,byte>(x =>
{
if (x.SequenceEqual(escapeSequence))
{
return new List<byte> { 0x7E };
{
else
{
return x;
}
});
Does that make any sense or am I missing something critical here?
There isn’t anything built-in like that. The first problem is that by passing an arbitrary
Func<IEnumerable<T>,T>to the enumerator, it won’t know how many bytes it will need to “take” and pass to the function. A more reasonable approach is shown below, where you can pass a sequence to be replaced, and the other sequence to replace, and do a simple search for that.