开发者

c# copying an arraylist to array

I would like to know how to send all of the information in 3 arraylists to an array.

Arraylist clubs = new Arraylist
Arraylist spades = new Arraylist
Arraylist hearts = new Arraylist.
int[] a开发者_如何学JAVArray = new int[52]

I got values for 1 to 13 in each of the arraylists, now I would like to copy all of the values for the three arraylists to an array[52].


clubs.CopyTo(array, 0);
spades.CopyTo(array, 13);
hearts.CopyTo(array, 26);
diamonds.CopyTo(array, 39);


var array = clubs.Concat(spades).Concat(heart).ToArray();

EDIT: Oops, TIL, that ArrayList is one of those old types that I've completly forgotten about. Don't bother with it anyway: Use List<T> instead:

List<int> clubs = new List<int>(){1, 2, 3};
List<int> hearts = new List<int>(){4, 5, 6};
List<int> spades = new List<int>(){7, 8, 9};
var array = clubs.Concat(hearts).Concat(spades).ToArray();  

Sorry for posting an answer that doesn't compile. But then again... The OP's didn't compile either... ;)


ArrayList clubs = new ArrayList();
ArrayList spades = new ArrayList();
ArrayList hearts = new ArrayList();

int[] array = new int[52];

clubs.ToArray(typeof(int)).CopyTo(array, 0);
spades.ToArray(typeof(int)).CopyTo(array, clubs.Count);
hearts.ToArray(typeof(int)).CopyTo(array, spades.Count + clubs.Count);

The code doesn't check for the length of each ArrayList, so make sure they are no longer than 13.


The is a CopyTo ArrayList method. There is also a ToArray method as well. The difference? USing ToArray returns the array, so creates it for you. The only thing is that you will need to cast it to an integer array in that case. Performance wise? Well they are both O(n) and both call Array.Copy anyway.

It depends whether you have the array created already as to which one you want to use. CopyTo has a few extra options that may be of interest if you are doing more than just a 1:1 copy.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜