In a string list how to split by every 2 character and insert a comma

319 views Asked by At

I have a list string which has values like below, could you please let me know how to split the list by every 2 character and insert a comma separated and assign the final list to another list.

var list1 = new List<string>() {"DVMNKL"};
var list2 = new List<string>() {"DV","MN","KL"};

Some time list1 can have only 2 character, at that time I should not split, I have to just assign to list2

1

There are 1 answers

2
Johnny On BEST ANSWER

You can use System.Linq to manage that.

int splitByCount = 2;
string s = new List<string> { "DVMNLS", "DVMNLS" };

var split = s.SelectMant(c => c) //flatten the list of strings to IEnumerable<char>
    .Select((c, index) => new {c, index})
    .GroupBy(x => x.index/splitByCount)
    .Select(group => group.Select(elem => elem.c))
    .Select(chars => new string(chars.ToArray()));

Console.WriteLine(string.Join(",", split));

the output

DV,MN,KL,DV,MN,KL