Brian Triplett
Brian Triplett

Reputation: 3532

Initialize a List<int> with LINQ query

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?

Upvotes: 3

Views: 5202

Answers (6)

Donut
Donut

Reputation: 112835

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.

Upvotes: 3

Tim Lloyd
Tim Lloyd

Reputation: 38464

This can be achieved using Enumerable.Range

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

Upvotes: 11

Random Dev
Random Dev

Reputation: 52290

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

Upvotes: 1

Quintin Robinson
Quintin Robinson

Reputation: 82355

You could use Enumerable.Range

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

Upvotes: 1

Chris Shain
Chris Shain

Reputation: 51359

Assuming MaxValue is always > MinValue,

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

Upvotes: 2

Adam Carr
Adam Carr

Reputation: 2986

You could use a collection initializer.

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

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

Upvotes: 1

Related Questions