Create List<int> with values at compile time

独自空忆成欢 提交于 2020-05-25 08:59:29

问题


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)?


回答1:


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);



回答2:


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();



回答3:


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.




回答4:


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.




回答5:


You can also do it like this, using System.Linq.Enumerable:

int[] categories = { 221, 222, 223, 224, 225, 226, 227, 228, 235, 236, 254, 255, 256 };        
var ticketsToProcess = categories.ToList();


来源:https://stackoverflow.com/questions/793000/create-listint-with-values-at-compile-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!