How to efficiently duplicate a specific value in a list

Viewed 109

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

3 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();

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.

A simple but maybe not optimal solution could be to combine the SelectMany and Repeat operators:

var result = source.SelectMany(x => Enumerable.Repeat(x, x == 16 ? 2 : 1));
Related