Creating a list with elements count dependable from the another list

Title may not be as accurate as I'd want it to. I'll show it to you using an example:

List<int> anotherList = new List<int>();
[0] 3
[1] 6
[2] 2
[3] 3
[4] 2
[5] 2
[6] 1

The List I want to create should contain elements multiplied by the elements in anotherList.

For example:

List<int> newList = new List<int>();
[0] 3
[1] 3
[2] 3
[3] 6
[4] 6
[5] 6
[6] 6
[7] 6
[8] 6
[9] 2
[10] 2
[11] 3
[12] 3
[13] 3
[14] 2
[15] 2
[16] 2
[17] 2
[18] 1

I know this list may seem completely useless for anyone but i really need it to move on with my program. Really would appreciate the help with this one!

Jon Skeet
people
quotationmark

LINQ makes this easy with SelectMany and Enumerable.Repeat:

var result = input.SelectMany(x => Enumerable.Repeat(x, x)).ToList();

The SelectMany is a flattening operation: for each input in the original sequence, generate a new sequence using the given projection... and the overall result is a sequence which contains all those "subsequences" as one flat sequence.

From there, you just need the projection - which in your case is "for an element x, the result is x, x times". That's easily done with Enumerable.Repeat(x, x).

people

See more on this question at Stackoverflow