Home > Backend Development > C++ > How to Efficiently Create Cloned Subarrays in C#?

How to Efficiently Create Cloned Subarrays in C#?

Mary-Kate Olsen
Release: 2025-01-18 20:43:39
Original
193 people have browsed it

How to Efficiently Create Cloned Subarrays in C#?

Efficiently create cloned subarrays in C#

When working with arrays, it is often necessary to create a subarray containing a specific range of elements from an existing array. While this can be achieved by manually looping and copying elements, there are more efficient and cleaner methods.

To create cloned subarrays, extension methods can be used. Here’s how to do it:

<code class="language-csharp">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;
}</code>
Copy after login

How to use it:

<code class="language-csharp">int[] data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] sub = data.SubArray(3, 4); // 包含 {3, 4, 5, 6}</code>
Copy after login

For cloned subarrays whose elements are complex objects, you can use serialization for deep copying:

<code class="language-csharp">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);
    }
}</code>
Copy after login

This method requires the object to be serializable.

The above is the detailed content of How to Efficiently Create Cloned Subarrays in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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