Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading