Reputation: 45931
I'm developing a WinForm application with C# and .NET Framework 4.7.1.
I'm doing this because there is always enough room in offsprint1
to add it crossoverParent2
:
private void Crossover(
List<byte> offsprint1,
List<byte> crossoverParent2,
int crossoverPoint)
{
for (int index = crossoverPoint, i = 0; index < offsprint1.Count; index++, i++)
offsprint1[index] = crossoverParent2[i];
}
But now, I'm going to change it and sometime there won't be enough room in offsprint1
. With the previous code, I will get an IndexOutOfRangeException
in offsprint1[index]
.
I've thought to use List.AddRange, but there isn't a version to set the index (crossoverPoint
) where I want to start replacing the content of offsprint1
with the contents of crossoverParent2
.
I want to replace the contents of the list from a given index (crossoverPoint
), and resize the list if there is not enough room to store the contents of crossoverParent2
. In other words:
(offspring1.Count - crossoverPoint) < crossoverParent2.Count
How can I do that?
Upvotes: 1
Views: 80
Reputation: 45931
Another way to do it:
private void Crossover(
List<byte> offspring1,
List<byte> parent2Slide,
int crossoverPoint)
{
int toRemove = offspring1.Count - crossoverPoint;
offspring1.RemoveRange(crossoverPoint, toRemove);
offspring1.AddRange(parent2Slide);
}
Upvotes: 0
Reputation: 37299
Instead of changing the given list I'd recommend returning a new list with the desired result. In this case - all items from first list until given index, replaced items from second list and eventually any other items from first list after those replaced ones.
You can do it like this:
offsprint1.Take(crossoverPoint) // Original items
.Concat(crossoverParent2) // Replaced items
.Concat(offsprint1.Skip(crossoverPoint + crossoverParent2.Count) // Rest of original items
As a side note as you wrote: "I've thought to use List.AddRange, but there isn't a version to set the index" then there exists a method List<T>.InsertRange
:
Inserts the elements of a collection into the List at the specified index.
As for your question from the comments. Simplest thing is to try it out:
List<int> data = new List<int> { 1,2,3,4,5};
data.InsertRange(2,new List<int> {6,7,8});
Console.WriteLine(string.Join(", ",data)); // 1, 2, 6, 7, 8, 3, 4, 5
Upvotes: 1
Reputation: 1669
There is no need to resize the list. You just have to check if the index already exists or not. Something like that:
var list1 = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var list2 = new List<int>() { 40, 50, 60 };
var position = 3;
foreach (var value in list2)
{
if (position < list1.Count)
{
list1[position] = value;
}
else
{
list1.Add(value);
}
++position;
}
list1
will have the values from 1, 2, 3, 40, 50, 60, 7, 8, 9.
Upvotes: 0