Set size of generic list via script?

I just started using lists and its a bit confusing to me.
How can I set the size of my list? Count is read only and Capacity doesn’t do it either.
With arrays you’d do something like:

array1.length = array2.length;

But how do you do it with generic lists?
I tried:

list1.Capacity = list2.Count;

or

list1 = new List<int>(list2.Count);

and some other variations, but it doesn’t resize it in the inspector;
I can do it manually but I wanna do it via script if possible.

I’ve read through the http://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx but couldn’t find anything that would let me do that.

I just started using them too. From my very limited knowledge, you can't set a permanent size. [link text][1] [1]: http://wiki.unity3d.com/index.php?title=Which_Kind_Of_Array_Or_Collection_Should_I_Use?#Generic_List

Yes I went through that too and nothing. Lets wait and see if anyone else can tell us if we can. xD Maybe we can make an empty array of some length and convert it into a list. I'm not sure, I can't find anything on that either. I'm liking lists tho, not faster than builtin arrays, but faster than javascript arrays, and have type casting, and more functions that builtin arrays don't.

2 Answers

2

You don’t explicitly set the size of a List; the size comes from the number of items in it. (Capacity is only for the internal size of the List and something you would rarely if ever use.) If you want a List with a particular number of items you can convert an array to a List.

list1 = new List<int>(new int[list2.Count]);

Aaand there's the answer I was expecting! xD I'm following a tutorial which uses javascript arrays, and doesn't use #pragma strict which makes it not work on mobile platforms, me thinks. So I decided to use lists instead and I'm trying to follow it as closely as possible because I know I'm bound to run into speed bumps at every step. xD Thank you!

Bleh, nothing should ever use Javascript arrays. ;) Especially not a tutorial, since that's likely to confuse people who aren't aware of the problems with them.

Well, at least it's straightforward enough in most cases to convert Javascript arrays to generic Lists...if you get stuck on anything just post another question.

Ok, thanks again! :D

Ding 100k.

This page comes up pretty early in searches for how to resize a list. So, here’s my solution — just stick this in a (possibly static) class somewhere, and it adds a Resize(n) method to the generic List.

public static void Resize<T>(this List<T> list, int newCount) {
	if (newCount <= 0) {
		list.Clear();
	} else {
		while (list.Count > newCount) list.RemoveAt(list.Count-1);
		while (list.Count < newCount) list.Add(default(T));
	}
}

Cleaner solution is to use Linq: http://stackoverflow.com/questions/31656460/c-sharp-enumerable-take-with-default-value