Chris
Chris

Reputation: 47

Sort list by index

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

Answers (4)

Johan
Johan

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

EZI
EZI

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

David Pilkington
David Pilkington

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

RePierre
RePierre

Reputation: 9566

If I understood you correctly, you need to use GroupBy() to get the lists:

var result = myString.Split('|').ToList()
    .GroupBy(c => c)
    .Select(g => g.ToList())

Here are the results in LinqPad:

Results

Upvotes: 8

Related Questions