Reputation: 47
I get a string: z|a|b|c|a|b|c|a|b|c
I would like three arrays or lists: arrayOne = a a a, arrayTwo = b b b, arrayThree = c c c
so far I split the string like this
List<string> myList = myString.Split('|').ToList();
z,a,b,c can be any string value
any help would be appreciated.
arrayOne = myListIndex 1,4,7
arrayTwo= myListIndex 2,5,8
arrayThree = myListIndex 3,6,9
but myList can be any length
Upvotes: 0
Views: 368
Reputation: 1026
Skip the first item and divide the rest into three lists, taking every 3rd element
var arrayOne = myList.Skip(1).Where((x, i) => i % 3 == 0).ToList();
var arrayTwo = myList.Skip(1).Where((x, i) => i % 3 == 1).ToList();
var arrayThree = myList.Skip(1).Where((x, i) => i % 3 == 2).ToList();
Upvotes: 0
Reputation: 15354
Skip the first item and use Index mod 3
to get the desired lists.
string myString = "z|a|b|c|a|b|c|a|b|c";
List<List<string>> result = myString.Split('|').Skip(1)
.Select((s, i) => new { s, i })
.GroupBy(x => x.i % 3)
.Select(g => g.Select(c => c.s).ToList())
.ToList();
Upvotes: 2
Reputation: 13620
You can use .GroupBy()
myList.GroupBy(a => a).Select(group => group.ToList());
This will be you a collection of lists that you want.
If you keep the groups you can see what Key
the collections are grouped by.
Upvotes: 0