Use extension methods to efficiently clone array subsets
When dealing with arrays, it is often necessary to create a new array containing some elements. While a loop can achieve this, using extension methods is a cleaner approach.
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; }
This extension method extends the T[]
type and returns a new array containing elements of the specified length starting at the specified index. For example:
int[] data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int[] sub = data.SubArray(3, 4); // 结果为 {3, 4, 5, 6}
Deep clone array subset
If you need a deep clone of a subset of an array (each element is also a copy), you can use serialization.
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); } }
Note that this deep cloning requires the object to be serializable via [Serializable]
or ISerializable
.
The above is the detailed content of How Can I Efficiently Clone a Subset of Array Elements in C# Using Extension Methods?. For more information, please follow other related articles on the PHP Chinese website!