How to add an element at middle of an array? I have tried searching on google but cannot find a way to do this without looping. Can anybody help me by providing a code snippet but please don't suggest using loop as the array is heavy and performance is the bottle neck here.
EDIT
actually i want that every odd index element gets copied to the even index.
Example
myarray[0] = "a";
myarray[1] = "b";
myarray[2] = "c";
Answer expected
myarray[0] = "a";
myarray[1] = "a";
myarray[2] = "b";
myarray[3] = "b";
myarray[4] = "c";
myarray[5] = "c";
How to add an element at middle of an array?
You can't add an element anywhere in an array. Once an array has been created, its size is fixed - you can modify elements, but you can't add or delete them.
You could use a List<T>
instead, which does allow for insertion - but which will need to copy the elements that occur after the insertion point.
You could potentially use a LinkedList<T>
instead, but then you'd need to loop in order to get to the right node.
You might want to consider using some kind of tree structure instead, which may make it easier to find the right spot and then insert the data.
Alternatively, consider a redesign - we don't have much context, but you might want to consider something like collecting all the data to start with, ignoring ordering, and then sorting it into the right order.
EDIT: For your example, I wouldn't use any sort of insertion - I'd create a new list from the old one, for example:
// Or use Enumerable.Repeat instead of creating an array for each element.
var newList = oldList.SelectMany(x => new[] { x, x }).ToList();
Or do it without LINQ:
var copies = 2; // Or whatever
var newList = new List<string>(oldList.Count * copies);
foreach (var item in oldList)
{
for (int i = 0; i < copies; i++)
{
newList.Add(item);
}
}
Fundamentally you're not going to make this any cheaper than O(N) where N is the number of items in the resulting list...
See more on this question at Stackoverflow