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?
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
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments