How to copy part of an array to another array in C#?
int[] b = new int[3];
Array.Copy(a, 1, b, 0, 3);
- a = source array
- 1 = start index in source array
- b = destination array
- 0 = start index in destination array
- 3 = elements to copy
copy part of an array into another array
Use System.Array.Copy:
string[] myArray = ....
string[] copy = new string[10];
Array.Copy(myArray, 2, copy, 0, 10);
Copy Arrays to Array
I try to copy a Int Array into 2 other Int Arrays with
The first thing that is important is that in this line :
unsortedArray2 = unsortedArray;
you do not copy the values of the unsortedArray
into unsortedArray2
. The =
is called the assignment operator
The assignment operator (=) stores the value of its right-hand operand in the storage location,
Now the second thing that you need to know to understand this phenomenon is that there are 2 types of objects in C# Reference Types and Value types
The documentation explains it actually quite nicely:
Variables of reference types store references to their data (objects), while variables of value types directly contain their data. With reference types, two variables can reference the same object; therefore, operations on one variable can affect the object referenced by the other variable.
The solution can be to use the Array.Copy method.
Array.Copy(unsortedArray, 0, unsortedArray2 , 0, unsortedArray.Length);
The CopyTo method would also work in this case
unsortedArray.CopyTo(unsortedArray2 , 0);
Note:this will work because the content of the array is a value type! If it would be also of reference type, changing a sub value of one of the items would lead also to a change in the same item in the destination array.
How to copy parts of an array to a new array. C#
is there also a way to give array
B
values 0, 1, 4, 5. so it gives me "A" "B" "E" and "F"
No, because B
is an array of string
s. However, you can start with a separate array of indexes, and copy from A
based on them:
int[] indexes = new[] {0, 1, 4, 5};
string[] B = indexes.Select(i => A[i]).ToArray();
How copy the data from a array to another array without overwrite
You should make total
a list because you want to extend it with new entries:
List<string> total = new List<string> { "Apple", "Banana", "Cat" };
And then you can use AddRange
to add all of the values from arrayA
:
total.AddRange(arrayA);
If you really need an array then this should work, though the List
option is still better:
string[] total = new {"Apple", "Banana", "Cat"};
string[] arrayA = new {"Donkey", "Ear", "Frog"};
total = total.Concat(arrayA).ToArray();
There is also an 'Array.Resize' method. Ultimately this just creates a new array and copies the data so it isn't really much better than the LINQ method above:
string[] total = new {"Apple", "Banana", "Cat"};
string[] arrayA = new {"Donkey", "Ear", "Frog"};
int initialTotalLength = total.Length;
// resize the array
Array.Resize(ref total, total.Length + arrayA.Length);
// append the new entries to the "empty" positions in the array
arrayA.CopyTo(total, initialTotalLength);
Fast way to copy part of an array into a List?
The List<T>(IEnumerable<T>)
constructor will use ICollection<T>.CopyTo
if the collection implements ICollection<T>
, which byte[]
will do.
That's not going to help directly if you only want to extract part of the array, but you could create your own ByteArraySegment
class implementing ICollection<byte>
and implement the CopyTo
operation using Buffer.BlockCopy
or whatever:
public class ByteArraySegment : ICollection<byte>
{
private readonly byte[] array;
private readonly int start;
private readonly int count;
public ByteArraySegment(...)
{
// Obvious code
}
public void CopyTo(byte[] target, int index)
{
Buffer.BlockCopy(array, start, target, index, count);
}
// Other ICollection<T> members
}
Then:
List<byte> bytes = new List<byte>(new ByteArraySegment(myArray, start, count));
(Or use AddRange
which has the same optimization.)
C#: Assign array to another array: copy or pointer exchange?
Assignment always just copies the value of one expression into a variable (or calls a property/indexer setter).
In your case, with this:
buffer1 = buffer2;
... the value of buffer2
is just a reference to a byte array. So after that assignment (and assuming no other assignments), changed made to the byte array "via" one variable will be visible "via" the other variable.
This isn't specific to array types - this is how reference types work all the way through .NET:
StringBuilder x = new StringBuilder();
StringBuilder y = x;
x.Append("Foo");
Console.WriteLine(y); // Foo
It's just a matter of understanding that arrays are always reference types.
c# - how to copy a section of byte[] to another array?
how about something like:
var byteArray = new byte[] { 1, 0, 1 };
var startIndex = 1;
var length = 2;
byteArray.Skip(startIndex).Take(length).ToArray();
How do I clone a range of array elements to a new array?
You could add it as an extension method:
public static T[] SubArray<T>(this T[] data, int index, int length)
{
T[] result = new T[length];
Array.Copy(data, index, result, 0, length);
return result;
}
static void Main()
{
int[] data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] sub = data.SubArray(3, 4); // contains {3,4,5,6}
}
Update re cloning (which wasn't obvious in the original question). If you really want a deep clone; something like:
public static T[] SubArrayDeepClone<T>(this T[] data, int index, int length)
{
T[] arrCopy = new T[length];
Array.Copy(data, index, arrCopy, 0, length);
using (MemoryStream ms = new MemoryStream())
{
var bf = new BinaryFormatter();
bf.Serialize(ms, arrCopy);
ms.Position = 0;
return (T[])bf.Deserialize(ms);
}
}
This does require the objects to be serializable ([Serializable]
or ISerializable
), though. You could easily substitute for any other serializer as appropriate - XmlSerializer
, DataContractSerializer
, protobuf-net, etc.
Note that deep clone is tricky without serialization; in particular, ICloneable
is hard to trust in most cases.
Related Topics
In C# Check That Filename Is *Possibly* Valid (Not That It Exists)
Fastest Way to Convert Image to Byte Array
How Much Memory Does a C#/.Net Object Use
How to Ensure a Form Displays on the "Additional" Monitor in a Dual Monitor Scenario
How to Set the Default Xml Namespace for an Xdocument
What Is the Worst Gotcha in C# or .Net
Mirroring Console Output to a File
How to "Multiply" a String (In C#)
Ef 4.1 - Code First - JSON Circular Reference Serialization Error
How to Round to the Nearest Whole Number in C#
Differencebetween a Property and a Variable
How to Catch a Specific SQLexception Error
How to Draw Directly on the Windows Desktop, C#
How to Use Use Late Binding to Get Excel Instance
How to Modify or Delete Items from an Enumerable Collection While Iterating Through It in C#
C# "Internal" Access Modifier When Doing Unit Testing
No Connection String Named 'Myentities' Could Be Found in the Application Config File