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 Query

More Query from same tag