score:5

Accepted answer

You can use Linq's Enumerable.Repeat with SelectMany:

List<int> newList = otherList
    .SelectMany(x => Enumerable.Repeat(x, x))
    .ToList();

The SelectMany extension method takes IEnumerable<T>s selected with a given predicate and flattens them into one IEnumerable<T>. (Not necessarily the same T of the IEnumerable<T> that the method was invoked for!)

The Enumerable.Repeat method, receives the amount of times to repeat a certain object and returns an IEnumerable of that object repeated.

score:10

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).


Related Articles