Hooked on LINQ

Hooked on LINQ - Developers' Wiki
for .NET Language Integrated Query

Quick Search

Advanced Search »

Range Operator

Modified: 2008/05/08 19:38 by samdnp - Categorized as: LINQ to Objects
Back to Standard Query Operators

Edit

Introduction

The Range operator generates a sequence of integral numbers.

Edit

Method Signatures

public static IEnumerable<int> Range(int start, int count)



Edit

Exceptions

Throws an ArgumentOutOfRange exception if count < 0, or start + count > int.MaxValue.

Edit

Pseudo-code

If count < 0 throw an ArgumentOutOfRange exception.
If start + count > int.MaxValue, throw an ArgumentOutOfRangeException.
Begin loop starting at 0.
Return an integer value equal to (start + loop counter). Resume execution from here when the next element is requested.

Edit

Loop count

0. This is a generation operator.This operator implements the standard deferred execution iterator pattern. This means, no looping will occur until the result is iterated over.

Edit

Code Samples

// Example showing how to generate a range starting at the value 10, for 20 elements. Added by Rob Philpott
using System;
using System.Linq;
 
namespace HookedOnLinq
{
    public class RangeExample
    {
        public static void Main()
        {
            var numbers = Enumerable.Range(10, 20);
            
            foreach (int x in numbers)
            {
                Console.WriteLine(x);
            }
            
            Console.ReadLine();
        }
    }
}
 
returns:
 
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29



Edit

Practical Example With Windows Forms

This example will fill a range of numbers in a ComboBox. You can use this for displaying years, day numbers or coordinates.
 
xComboBox.DataSource = Enumerable.Range(0, 15).ToArray();
yComboBox.DataSource = Enumerable.Range(0, 15).ToArray();
 

There is a screenshot at the article: LINQ Enumerable.Range Practical Example (by Sam Allen)

If you would like to comment on this page, click on the Discuss button located on the top-right of each page. Feel free to edit any mistakes or ommissions you find. If you have an objection or find in-appropriate content then contact the administrator. This website is not affiliated with Microsoft®, all content and opinions are those of the specific author and some advice, solutions and article may contain un-intentional errors - please use care. Powered by ScrewTurn Wiki version 2.0.33. Some of the icons created by FamFamFam.