This simple example shows how to use LINQ to Objects to query a collection of Integers. Some readers might find it odd to speak of querying an array of numbers, but collections contain data just as a database or an XML file contains data. A key feature of LINQ is that it allows you to use a similar syntax to query databases, XML, or a data structure in your program such as a collection of integers.

The C# 3.0 feature called a Collection Initializer provides a handy shorthand way to populate a collection. Here is how to automatically initialize a list of numbers:

List<int> list = new List<int>() { 1, 2, 3 };

Listing One shows a complete program demonstrating how to write a LINQ query against this collection. The query selects all the numbers in the collection that are smaller than 3 and prints them to the screen.

Listing One: A simple numeric query that returns the values 1 and 2.

using System;
using System.Collections.Generic;
using System.Linq;

namespace NumericQuery
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> list = new List<int>() { 1, 2, 3 };

            var query = from number in list
                        where number < 3
                        select number;

            foreach (var number in query)
            {
                Console.WriteLine(number);
            }
        }
    }
}

The centerpiece of the code shown in Listing 1 is the LINQ query itself, which is called a query expression:

var query = from number in list
            where number < 3
            select number;

On the left of the equals operator you see the words “var query.” The new keyword var tells the compiler to use type inference to infer the type of the identifier query from the expression on the right of the operator. This new keyword eliminates the need to guess the type of the data returned from a LINQ query, or from most other expressions. Just type the keyword var and let the compiler do the rest of the work for you.

On the right side of the equals operator you see the query itself:

  from number in list
  where number < 3
  select number;

All query expressions begin with the keyword from, and they generally end with line that begins with the keyword select. This particular query expression asks the compiler to iterate over the numbers in the list, returning only those that are smaller than 3. A foreach loop iterates over the results of the query. As mentioned early, this loop prints out the numbers 1 and 2.

This simple program introduced three key concepts:

  1. Collection Initializers
  2. Type Inference
  3. Query Expressions
kick it on DotNetKicks.com