Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert duplicates values linq

Tags:

c#

linq

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?

like image 817
DrkDeveloper Avatar asked Jun 04 '18 10:06

DrkDeveloper


1 Answers

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)));
like image 168
Tim Schmelter Avatar answered Oct 09 '22 04:10

Tim Schmelter