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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With