Search code examples
c#ref.net-7.0

GetRange of List as Reference


I want to get a sub-list from the list and perform an operation on it. And the result should be applied to the main list

var myNumber = new List<int>() { 1, 5, 9, 7, 2, 8, 2 };
var subNumbers = myNumber.GetRange(2, 4); // { 9, 7, 2, 8 }
for (int i = 0; i < subNumbers.Count; i++)
{
    subNumbers[i] = (int)Math.Pow(subNumbers[i], 2); // {81, 49, 4, 64 }
}

// For example, applied to 'myNumbers'

WriteLine(string.Join(", ", myNumbers)); // I want the output to be: { 1, 5, 81, 49, 4, 64, 2 }

Solution

  • You can use CollectionsMarshal.AsSpan<T>(List<T> list).

    var myNumber = new List<int>() { 1, 5, 9, 7, 2, 8, 2 };
    var subNumbers = CollectionsMarshal.AsSpan(myNumber).Slice(2, 4);
    for (int i = 0; i < subNumbers.Length; i++)
    {
        subNumbers[i] = (int)Math.Pow(subNumbers[i], 2)
    }
    

    See on SharpLab.


    The MSDN page has the warning:

    Items should not be added or removed from the List<T> while the Span<T> is in use.

    Make sure you heed that warning! If you add items from the List<T> then the backing array might be re-allocated, and the Span<T> will point to memory which is not longer being used by the List<T>. If you remove items which were in view of the Span<T>, then the Span<T> will not be updated to exclude the removed items, and may still contain them.