Home > OS >  How would you convert List<T> to Vector<T> C#
How would you convert List<T> to Vector<T> C#

Time:02-10

I'm using the vectors C# library using System.Numerics; I need to convert List to a Vector

I've tried implicitly and explicitly converting the type but it does not have inbuilt compatibility. I have read the documentation looking for a method that can do do this conversion, but didn't find any suitable.

I know I could achieve this conversion using a simple for loop but doing this conversion many times within my program seems terribly inefficient and I'm wondering if anyone knows of a better way to get the same result.

CodePudding user response:

Vector<T> has a constructor which takes a Span<T>, and CollectionsMarshal.AsSpan lets you get a Span<T> from a List<T>.

E.g.:

var list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8 };
var vector = new Vector<int>(CollectionsMarshal.AsSpan(list));

See on SharpLab.

This results in a single memory copy from the contents of the array backing the List<T>, to the memory backing the Vector<T>.

Heed the warnings in the docs for CollectionsMarshal.AsSpan: it returns a reference to the array which is currently backing the List<T>, but that will change if the list is updated. For just taking a snapshot for copying into a Vector<T>, however, it's fine.

  • Related