Populating a list of integers in .NET.

I need a list of integers from 1 to x, where x is user defined. I could build it with a for loop, for example, assuming x is an integer earlier:

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

It seems dumb, of course, a more elegant way to do this, is something like a PHP range method

+60
list c # integer
Sep 08 '08 at 5:45
source share
4 answers

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

Creates a sequence of number integrals within a given range.

+70
Sep 08 '08 at 5:49
source share

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

+33
Sep 08 '08 at 5:48
source share

I am one of many who have a blog about the ruby-esque method. For the extension you can write if 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 a list of integers like

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

or

 List<int> = 1.To(x).ToList(); 
+15
Sep 08 '08 at 8:58
source share

Here is a short method that returns a list of integers.

  public static List<int> MakeSequence(int startingValue, int sequenceLength) { return Enumerable.Range(startingValue, sequenceLength).ToList<int>(); } 
0
Apr 6 '16 at 21:04
source share



All Articles