Home > Backend Development > C++ > How Can I Efficiently Clone a Subset of Array Elements in C# Using Extension Methods?

How Can I Efficiently Clone a Subset of Array Elements in C# Using Extension Methods?

Barbara Streisand
Release: 2025-01-18 20:22:08
Original
179 people have browsed it

How Can I Efficiently Clone a Subset of Array Elements in C# Using Extension Methods?

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;
}
Copy after login

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}
Copy after login

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);
    }
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template