Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.ToArray() changes the dimension of my array

Tags:

arrays

string

c#

In my C# program I've created an array of string:

var arrayTest = new string[20];

I need to copy in it some string that I retrive from a List containing 10 strings.

arrayTest = listTest.ToArray();

This works but .ToArray() changes the dimension of my array based on the number of element in the list.

I need to maintain the same size (20) and have the 10 strings and the 10 null (or whatever value..)

Is there a way to accomplish this other than loop listTest ?

like image 410
SilentRage47 Avatar asked Dec 19 '25 19:12

SilentRage47


2 Answers

Assuming that your list is generic, you can just use its List<T>.CopyTo() method:

listTest.CopyTo(arrayTest);

Rather than the other answers which create another array just to copy from it and then throw it away.

Even for non-generic lists, there are Copy methods on most such classes that, again, allow you to copy the data directly into a target array, rather than calling ToArray first.

like image 97
Damien_The_Unbeliever Avatar answered Dec 22 '25 07:12

Damien_The_Unbeliever


You should either use Array.Copy or List<T>.CopyTo

// You can copy either 'List<T>' or 'Array' by using this
Array.Copy(listTest.ToArray(), arrayTest, listTest.Length);

or the method below inspired by Damien_The_Unbeliever

// You can copy 'List<T>' by using this, but it doesn't require a 'ToArray()' function
// It's better to use this if you're copying with 'List<T>'
listTest.CopyTo(arrayTest)

Using the above codes copies the listText's content to arrayTest, and it doesn't modify the rest of the values inside arrayTest.

But should make sure the size of arrayTest is longer or same as listTest's length, otherwise it'll throw an exception.

Why your code didn't work

The original code you have:

arrayTest = listTest.ToArray();

This makes the arrayTest points to a whole new reference, so the size 20 doesn't make any sense, since the array with length 20 will be garbage collected afterwards. Changing 20 to different sizes still results the same.

like image 23
J3soon Avatar answered Dec 22 '25 07:12

J3soon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!