1

I have a list of strings. For instance, the list is {"AbcXYZZ","DEFG","HIJKL","MNOPQR"}. I want to check if the current string's length is greater than 4, then it will divide string into N substrings(strings of length 4). The final output should be like this: {"AbcX","YZZ","DEFG","HIJK","L","MNOP","QR"}

I can use select function to process the pipeline, but I could not think of a way to add the substrings just after the parent string. Any help is appreciated

Ali Ahmad
  • 23
  • 3

1 Answers1

0

Try using SelectMany.

For splitting the strings I used the answer found here.

var list = new List<string> { "AbcXYZZ", "DEFG", "HIJKL", "MNOPQR" };

var output = list.SelectMany(x => x.Length > 4 ?
    _split(x, 4) :
    new string[] { x });

static IEnumerable<string> _split(string str, int chunkSize) =>
    Enumerable
        .Range(0, (str.Length + chunkSize - 1) / chunkSize)
        .Select(i => str.Substring(i * chunkSize, Math.Min(str.Length - (i * chunkSize), chunkSize)));

Console.WriteLine(String.Join(";", output));

outputs:

AbcX;YZZ;DEFG;HIJK;L;MNOP;QR
stuzor
  • 2,275
  • 1
  • 31
  • 45
  • This is perfect for my use case. Can you explain this code a bit? – Ali Ahmad Aug 21 '22 at 23:13
  • Select operates on an enumerable set of items, allowing you to process each item in the set and return a single object for each. SelectMany also operates on an enumerable set of items, but allows you to return multiple values for each item in the set, and the return value from SelectMany aggregates all the values into a single return set. – stuzor Aug 23 '22 at 06:36