Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating a list of integers in .NET

I need a list of integers from 1 to x where x is set by the user. I could build it with a for loop eg assuming x is an integer set previously:

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

This seems dumb, surely there's a more elegant way to do this, something like the PHP range method

like image 290
Glenn Slaven Avatar asked Sep 08 '08 05:09

Glenn Slaven


People also ask

How do you populate a list in C#?

Well, you can just put var list = new List<IMyCustomType>(); list. Add(new MyCustomTypeOne()); list. Add(new MyCustomTypeTwo()); list. Add(new MyCustomTypeThree()); on one line.

Can you add a list to a list C#?

Use the AddRange() method to append a second list to an existing list. list1. AddRange(list2); Let us see the complete code.


3 Answers

If you're using .Net 3.5, Enumerable.Range is what you need.

Generates a sequence of integral numbers within a specified range.

like image 112
jfs Avatar answered Sep 28 '22 10:09

jfs


LINQ to the rescue:

// Adding value to existing list
var list = new List<int>();
list.AddRange(Enumerable.Range(1, x));

// Creating new list
var list = Enumerable.Range(1, x).ToList();

See Generation Operators on LINQ 101

like image 41
aku Avatar answered Sep 28 '22 09:09

aku


I'm one of many who has blogged about a ruby-esque To extension method that you can write if you're using C#3.0:


public static class IntegerExtensions
{
    public static IEnumerable<int> To(this int first, int last)
    {
        for (int i = first; i <= last; i++)
{ yield return i; } } }

Then you can create your list of integers like this

List<int> = first.To(last).ToList();

or

List<int> = 1.To(x).ToList();
like image 30
Samuel Jack Avatar answered Sep 28 '22 10:09

Samuel Jack