Search code examples
c#arraysdimensions

How to convert the specific law of one-dimensional array into two-dimensional array?


Like this

string[]  strarry = [12, 34, A1, FE, 12, 34, EA, 0, FE]

12 is the beginning , FE is the end, Turn into

string strarry = [[12,34,A1,FE], [12,34,EA,0,FE]];

The distance from 12 to FE is not necessarily fixed (4)

How can I do it? Thank you


Solution

  • If I've understood you right (you want to obtain jagged array string[][] from ordinal one - string[]), you can try Linq in order to GroupBy items into subarrays:

      using System.Linq;
    
      ...
    
      string[] strarry = new string[]
        {"12", "34", "A1", "FE", "12", "34", "EA", "0", "FE"};
    
      // Here we exploit side effects, be careful with them
      int groupIndex = 0;
    
      string[][] result = strarry
        .GroupBy(value => value == "FE" ? groupIndex++ : groupIndex)
        .Select(group => group.ToArray())
        .ToArray();
    

    Let's have a look:

      string report = string.Join(Environment.NewLine, result
        .Select(line => "[" + string.Join(", ", line) + "]"));
    
      Console.Write(report);
    

    Outcome:

    [12, 34, A1, FE]
    [12, 34, EA, 0, FE]