0

I have introduced the notion of blocks into my system. Each block can be split into sub-blocks.
I thought of a few ways to create or keep track of the sub-blocks within a block and one option could be to have this (any better suggestion is welcome):

// // Dictionary <sub-block-number, payload>
Dictionary <UInt16, List<byte>> _payloads { get; set; } = new Dictionary<UInt16, List<byte>>();

Now I have no problem adding things to the dictionary, but retrieving the combined payload into a byte[] is causing me problem. I have also seen a bunch of things on stack overflow (see here) using Linq, but I am not sure it is the right way to go as some people say it is very inefficient. In all cases, none of these answers return a byte[].
Here is what I would like to implement:

// Get combined payload from _payloads dictionary
public byte[] GetTotalPayload()
{ .. }

EDIT

The Lists in the dictionary will be added incrementally one by one from "sub-block-number" = 0 to N. Not sure if when combining to List it is important to specify that the key has to be ordered incrementally? Probably not.

stackMeUp
  • 522
  • 4
  • 16
  • 1
    It's not clear 1) what the goal with retrieving the byte[] is (if it's writing to a file, writing direct to a file would be more efficient). 2) if there's a specific way in which each entry in the dictionary has to be combined. Can we just take any `List` for the first item? – ProgrammingLlama Jun 23 '20 at 09:18
  • @John, what file? Never mentioned a file. Just how to combine all the lists from the dictionary – stackMeUp Jun 23 '20 at 09:23
  • @John, What? I was not being rude. Sorry it came out that way :-) I was editing my question as you were answering. The ordering is a very good point, which does not matter too much, but probably worth taking care of it anyways. Thanks. – stackMeUp Jun 23 '20 at 09:29

2 Answers2

3

Using Enumerable.SelectMany to flatten the values into a single array.

public byte[] GetTotalPayload()
{
    return _payloads.SelectMany(kvp => kvp.Value).ToArray();
}
Johnathan Barclay
  • 18,599
  • 1
  • 22
  • 35
1

You can just flatten every list from dictionary value into single one using SelectMany and convert to array

var payload = _payloads.SelectMany(kvp => kvp.Value).ToArray();

It'll work if the sub-block numbers are really consecutive and sub-blocks itself aren't overlapped. You may also order the items by number OrderBy(kvp => kvp.Key) before flatten the values

Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66