Building an integer sequence using the Range operator in LINQ C#

Say you need a list of integers from 1 to 10. The traditional way is the following:

List<int> traditional = new List<int>();
for (int i = 1; i <= 10; i++)
{
	traditional.Add(i);
}

There’s a more concise way to achieve this with the static Range method which accepts two parameters. The first integer in the sequence and a count variable which defines the number of elements in the list. The step parameter is 1 by default and cannot be overridden:

IEnumerable<int> intRange = Enumerable.Range(1, 10);
foreach (int i in intRange)
{
	Console.WriteLine(i);
}

This will print the integers from 1 to 10.

Say you need an integer list from 100 to 110 inclusive:

IEnumerable<int> intRange = Enumerable.Range(100, 11);

View the list of posts on LINQ here.

Advertisements

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: