开发者

Initialize a List<int> with LINQ query

开发者 https://www.devze.com 2023-03-29 15:29 出处:网络
I am initializing a List<int> in a constructor by storing two simple constants, MinValue and MaxValue as such:

I am initializing a List<int> in a constructor by storing two simple constants, MinValue and MaxValue as such:

private const int MinValue = 1;
private const int MaxValue = 100;

private List<int> integerList = new List<int>();

public Class()
{
    for (int i = MinValue ; i < MaxValue ; i++)
    {
        integerList .Add(i);
    }
}

Is there a way to just initialize the list with a simple LINQ query? Since a List<T> can be constructed with an IEnumerable<T>, does a 开发者_运维知识库query of the following form exist?

private List<int> integerList = new List<int>(<insert query here>);

Is this even possible?


This can be achieved using Enumerable.Range

List<int> integerList = Enumerable.Range(MinValue, MaxValue - MinValue).ToList();


Just use the Enumerable.Range(int start, int count) method:

Generates a sequence of integral numbers within a specified range.

A simple example, using your MinValue and MaxValue variables:

List<int> integerList = Enumerable.Range(MinValue, MaxValue - MinValue).ToList();

Note that if MaxValue is less than MinValue, the count parameter will be less than zero and an ArgumentOutOfRangeException will be thrown.


Assuming MaxValue is always > MinValue,

var integerList = Enumerable.Range(MinValue, MaxValue-MinValue).ToList();


You could use a collection initializer.

http://msdn.microsoft.com/en-us/library/bb384062.aspx

private List integerList = new List{MinValue, MaxValue};


You could use Enumerable.Range

List<int> integerList = Enumerable.Range(MinValue, MaxValue - MinValue).ToList();


Try IEnumerable.Range(MinValue, MaxValue-MinValue).ToList(): MSDN

0

精彩评论

暂无评论...
验证码 换一张
取 消