Reputation: 43
Hi I wish to instantiate a list array with the array size of 1000 and the initial capacity of each list that store in the array of 500.
I try the following code,
static List<string>[] myList = new List<string>(500)[1000];
it gives me the exception:
Cannot implicitly convert type 'string' to 'System.Collections.Generic.List[]
but if I just specify
static List<string>[] myList = new List<string>[1000];
there is no problem...but with this, I am not specifying the initial capacity of each list that store in the array.
In List Array, how do we specify initial capacity of each list that store in the array?
Upvotes: 4
Views: 71
Reputation: 64
There's not a way to do it in one statement. Since you've got an array of objects, you'll need to initialize each object separately:
static List<string>[] myList = new List<string>[1000];
// in static constructor:
for(int i = 0; i<myList.Length; i++)
{
myList[i] = new List<string>(500);
}
Upvotes: 4
Reputation: 101701
You can do it in one statement using LINQ:
Enumerable.Range(0, 1000).Select(x => new List<string>(500)).ToArray();
Of course you should put this in a constructor or a method.Like this:
class Foo
{
private static List<string>[] myList;
static Foo()
{
myList = Enumerable.Range(0, 1000)
.Select(x => new List<string>(500)).ToArray();
}
}
Upvotes: 1