Search code examples
c#arraysarraylistsplitgroup

Split comma string array ever 10th comma


Hey all I am trying to figure out a better way to split my comma separated string code into sections:

Example: 31,139,8,0,0,0,0,0,4,0,164,188,233,139,121,45,100,253,235,255,225,212,147,233,105,231,15

This is my code I use to do the formating:

List<string> valueList = "31,139,8,0,0,0,0,0,4,0,164,188,233,139,121,45,100,253,235,255,225,212,147,233,105,231,15".Split(',').ToList();
List<string> groupedBy10 = new List<string>();

while (valueList.Any()) {
    groupedBy10.Add(string.Join(",", valueList.Take(10)) + ",");
    valueList = valueList.Skip(10).ToList();
}

groupedBy10[groupedBy10.Count - 1] = groupedBy10[groupedBy10.Count - 1].TrimEnd(',');
string newOutput = string.Join(Environment.NewLine, groupedBy10.ToArray());

And this is the newOutput output:

31,139,8,0,0,0,0,0,4,0,
164,188,233,139,121,45,100,253,235,255,
225,212,147,233,105,231,15

Is there a better way of doing this? Perhaps a Regex or Linq way thats shroter/faster?


Solution

  • You could use GroupBy with integer division:

    IEnumerable<IEnumerable<string>> groupedBy10 = valueList
        .Select((s, ix) => (String:s,Index:ix))
        .GroupBy(x => x.Index / 10)
        .Select(g => g.Select(x => x.String));
        
    IEnumerable<string> flattened = groupedBy10.Select(l => string.Join(",", l));
    string newOutput = string.Join(Environment.NewLine, flattened);
    

    Side-note: to remove the comma at the end of the last string, why don't you use this String.Split overload? No need to remove it at the end.

    List<string> valueList = "31,139,8,0,0,0,0,0,4,0,164,188,233,146,163,74,178,46,2,250,123,159,167,168,187,174,109,"
        .Split(new[]{','}, StringSplitOptions.RemoveEmptyEntries)
        .ToList();