Really, how can I do it? This doesn't work:
List<object>[] myList= new List<object>[100](500);
Really, how can I do it? This doesn't work:
List<object>[] myList= new List<object>[100](500);
You could try something like this:
var array = Enumerable.Range(0,100).Select(n=>new List<object>(500)).ToArray();
Here we use the List<T> constructor with one argument, the List's capacity. Please have a look here.
ToArray doesn't know that it will always have 100 elements, so you'll create a bunch of unnecessary intermittent arrays based on default start small and double the size once limit reached heuristics.Old style loop will do the trick:
List<object>[] myList= new List<object>[100];
for(int i = 0; i < 100; i++)
{
myList[i] = new List<object>(500);
}
You're not constructing the actual lists, just allocating space for storing references to them. You can only set the capacity when constructing the list objects.
You could wrap the array in another class and construct the lists lazily as they're needed:
class ListArray {
private readonly List<object>[] _lists;
private readonly int _capacity;
public ListArray(int size, int capacity) {
_lists = new List<object>[size];
_capacity = capacity;
}
public List<object> this[int ix] {
get {
if( _lists[ix] == null )
_lists[ix] = new List<object>(capacity);
return _lists[ix]
}
}
}
Then use it like
var myList = new ListArray(100, 500);
myList[0].Add(someObject);