Insert duplicates values linq

  • A+
Category:Languages

In a collection of values

[0, 2, 25, 30] 

I'm trying to do with linq

[0, 0, 0, 2, 2, 2, 25, 25, 25, 30, 30, 30] //Replicate 2 times (values repeated 3 times) 

Is there someway to do it with linq?

 


With value types it's easy, just use Enumerable.Repeat:

var result = collection.SelectMany(x => Enumerable.Repeat(x, 3)); 

If it was an array use ToArray if it was a list use ToList at the end.

With reference types it depends if you really want the same reference, then you can also use Repeat. Otherwise you need to create "deep-clones" of the instance, for example by using a copy constructor if available:

var result = collection     .SelectMany(x => Enumerable.Range(1, 3).Select(i => new YourType(x))); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: