Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently duplicate a specific value in a list

Tags:

arrays

c#

list

linq

In C# how can I duplicate a value in a list? I have found tons of solution smart solutions (especially in Linq) for how to remove but none on how to duplicate and in any case couldn't adapt to the code to my needs.

E.g. if I want to duplicate 16 --> Lst {0 0 12 13 16 0 3} ---> {0 0 12 13 16 16 0 3}

I wouldn't have to cycle on them but would prefer a single instruction

Thanks for helping

Patrick

like image 480
Patrick Avatar asked Dec 06 '25 06:12

Patrick


2 Answers

You can write your own extension method that you can use the same way as the default LINQ methods:

public static IEnumerable<T> Duplicate<T>(this IEnumerable<T> input, T toDuplicate)
{
    foreach(T item in input)
    {
        yield return item;
        if(EqualityComparer<T>.Default.Equals(item, toDuplicate))
        {
            yield return item;
        }
    }
}

The usage is

var test = new List<int>() { 0, 0, 12, 13, 16, 0, 3 };
var duplicated = test.Duplicate(16).ToList();
like image 161
SomeBody Avatar answered Dec 07 '25 22:12

SomeBody


try this


list.Insert((list.FindIndex(a => a== valueToBeDuplicated) + 1), valueToBeDuplicated));

so the FindIndex(a => a == valueToBeDuplicated) will get the index, then by adding + 1 will insert it on the next index.

like image 45
Gabriel Llorico Avatar answered Dec 07 '25 21:12

Gabriel Llorico