c# – C #. Split the list into intervals

Question:

There are lists of the form:

0 0 0 1 0 1 1 1 1 0 0 2 2 0 1 1 0 0

It is necessary to split this list into intervals, excluding zeros. The output is an array of intervals consisting of consecutive identical elements.

For instance:

[0] = 1, [1] = 1 1 1 1, [2] = 2 2, [3] = 1 1

What is the best way to do this?

Answer:

  1. Add zeros to the beginning and end of the list so that the beginning and end are explicitly delimited.
  2. We get the indices of the positions in which the zeros are located.
  3. We get sequences lying between zeros.
  4. Let's return all non-empty sequences.
    Like that:

     var baseList=new int[] { 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 2, 2, 0, 1, 1, 0, 0 }; var surrList = new List<int> { 0 }; surrList.AddRange(baseList); surrList.Add(0); var zeroindex = surrList.Select((s, i) => new {s, i}) .Where(x => xs == 0).Select(x=>xi).ToArray(); var result = zeroindex.Select((z, zi) => surrList.ToArray() .Where((s, si) => zi<zeroindex.Length-1 && si>zeroindex[zi] && si<zeroindex[zi+1] ).ToList()) .Where(x=>x.Any()).ToList();
Scroll to Top