It is possible to create an array at compile time like;
int[] myValues = new int[] { 1, 2, 3 } ;
But I would like to do something like this;
List<int> myValues = new List<int>() { 1, 2, 3 };
The compiler says No. Is there a way to do this (C# 2.0) without using LINQ (C# 3.0)?
In the above example, List<int> primeNumbers = new List<int>(); creates a list of int type. In the same way, cities and bigCities are string type list. You can then add elements in a list using the Add() method or the collection-initializer syntax.
Add(new string[] { "Id", "Name", "Age" }); for(int i=0; i<list. Count; i++) for(int j=0; j<list[i]. Count(); j++) Console. WriteLine(list[i][j]); // simpler with foreach foreach(var l in list) foreach(string s in l) Console.
List<int> myValues = new List<int>(new int[] { 1, 2, 3 } );
This will create an intermediate array however so there may be a more efficient way of doing the same thing.
EDIT:
John Feminella suggested creating a factory method to accept a list of parameters and return a List which you could implement as follows:
List<T> CreateList<T>(params T[] values) { return new List<T>(values); }
which you can use as follows:
List<int> myValues = CreateList(1, 2, 3);
Patrick has the answer you are looking for. But I wanted to add a little bit. If you want to do longer ranges of numbers and don't feel like typing them out by hand, you should look at the Enumerable.Range method. It can be used to generate a range of sequential numbers at runtime. For instance, your sample could have been written as follows
var list = Enumerable.Range(1,3).ToList();
The way you suggests was first introduced in C# 3.0 (has nothing to do with LINQ, it was a language feature that was introduced).
There's no "shortcut" (list initialization) in C# 2.0 to do just that, either new up the list and then add the numbers manually via myValues.Add, or you could do the following:
int[] arrMyValues = new int[] {1, 2, 3};
List<int> myValues = new List<int>(arrMyValues);
List of T can take an IEnumerable of T in it's constructor, of which it'll include all T's in that IEnumerable in the list created, seeing as int[] implements IEnumerable of T you can "mix and match" the features like so.
Besides that, there's no way in C# 2.0 to do a such thing that you describe.
The collection initializers are just syntax sugar, so you can use them in an application targeted at 2.0 if you compile with the 3.0 compiler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With