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
CodePudding user response:
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