Homepage image
Sample of the Day RSS Feed

Sample Downloads
C# version:
http://code.msdn.microsoft.com/CSLinqToObject-ae11b24b
VB version: http://code.msdn.microsoft.com/VBLinqToObject-74665c0a

Today’s code sample demonstrates “LINQ to Objects”.  The term "LINQ to Objects" refers to the use of LINQ queries with any IEnumerable or IEnumerable<T> collection directly, without the use of an intermediate LINQ provider or API such as LINQ to SQL or LINQ to XML. You can use LINQ to query any enumerable collections such as List<T>, Array, or Dictionary<TKey, TValue>. The collection may be user-defined or may be returned by a .NET Framework API. This example illustrates how to write Linq to Object queries using Visual C# and VB.NET.

imageYou can find more code samples that demonstrate the most typical programming scenarios by using Microsoft All-In-One Code Framework Sample Browser or Sample Browser Visual Studio extension. They give you the flexibility to search samples, download samples on demand, manage the downloaded samples in a centralized place, and automatically be notified about sample updates. If it is the first time that you hear about Microsoft All-In-One Code Framework, please watch the introduction video on Microsoft Showcase, or read the introduction on our homepage http://1code.codeplex.com/.

 

Introduction

The term "LINQ to Objects" refers to the use of LINQ queries with any IEnumerable or IEnumerable<T> collection directly, without the use of an intermediate LINQ provider or API such as LINQ to SQL or LINQ to XML. You can use LINQ to query any enumerable collections such as List<T>, Array, or Dictionary<TKey, TValue>. The collection may be user-defined or may be returned by a .NET Framework API.

In a basic sense, LINQ to Objects represents a new approach to collections. In the old way, you had to write complex foreach loops that specified how to retrieve data from a collection. In the LINQ approach, you write declarative code that describes what you want to retrieve.

In addition, LINQ queries offer three main advantages over traditional foreach loops:

1.They are more concise and readable, especially when filtering multiple conditions.

2.They provide powerful filtering, ordering, and grouping capabilities with a minimum of application code.

3.They can be ported to other data sources with little or no modification.

In general, the more complex the operation you want to perform on the data, the more benefit you will realize by using LINQ instead of traditional iteration techniques.

This example illustrates how to write Linq to Object queries using Visual C# and VB.NET. First, it builds a class named Person. Person inculdes the ID, Name and Age properties. Then the example creates a list of Person which will be used as the datasource. In the example, you will see the basic Linq operations like select, update, orderby, max, average, etc. 

 

Running the Sample

image

 

Using the Code

1. Define the Person class that includes the ID, Name, and Age properties.

class Person 
{ 
    public Person(int id, string name, int age) 
    { 
        this.id = id; 
        this.name = name; 
        this.age = age; 
    } 
 
 
    private int id; 
 
 
    /// <summary> 
    /// Person ID 
    /// </summary> 
    public int PersonID 
    { 
        get { return this.id; } 
        set { this.id = value; } 
    } 
 
 
    private string name; 
 
 
    /// <summary> 
    /// Person name 
    /// </summary> 
    public string Name 
    { 
        get { return this.name; } 
        set { this.name = value; } 
    } 
 
 
    private int age; 
 
 
    /// <summary> 
    /// Age that ranges from 1 to 100 
    /// </summary> 
    public int Age 
    { 
        get { return this.age; } 
        set 
        { 
            if (value > 0 && value <= 100) 
                this.age = value; 
            else 
                throw new Exception("Age is out of scope [1,100]"); 
        } 
    } 
} 
 

2. Build a list of Person to be used as the data source.

       ///////////////////////////////////////////////////////////////////// 
       // Build the Person list that serves as the data source. 
       // 
       List<Person> persons = new List<Person>(); 
 
 
       persons.Add(new Person(1, "Alexander David", 20)); 
       persons.Add(new Person(2, "Aziz Hassouneh", 18)); 
       persons.Add(new Person(3, "Guido Pica", 20)); 
       persons.Add(new Person(4, "Chris Preston", 19)); 
       persons.Add(new Person(5, "Jorgen Rahgek", 20)); 
       persons.Add(new Person(6, "Todd Rowe", 18)); 
       persons.Add(new Person(7, "SPeter addow", 22)); 
       persons.Add(new Person(8, "Markus Breyer", 19)); 
       persons.Add(new Person(9, "Scott Brown", 20)); 

3. Use Linq to perform the query operation.

       ///////////////////////////////////////////////////////////////////// 
       // Query a person in the data source. 
       // 
       var Todd = (from p in persons 
                   where p.Name == "Todd Rowe" 
                    select p).First(); 
       // [-or-] 
       // Use extension method + lambda expression directly 
       //var Todd = persons.Where(p => p.Name == "Todd Rowe").First(); 
 
 
       Console.WriteLine("Todd Rowe's age is {0}", Todd.Age); 

4. Use Linq to perform the Update operation.

///////////////////////////////////////////////////////////////////// 
// Perform the Update operation on the person's age. 
// 
Todd.Age = 21; 
Console.WriteLine("Todd Rowe's age is updated to {0}", (from p in persons 
                                                        where p.Name == "Todd Rowe" 
                                                    select p).First().Age); 

5. Use Linq to perform the Order operation.

      ///////////////////////////////////////////////////////////////////// 
      // Sort the data in the data source. 
      // Order the persons by age 
      var query1 = from p in persons 
                   orderby p.Age 
                   select p; 
 
 
      Console.WriteLine("ID\tName\t\tAge"); 
 
 
      foreach (Person p in query1.ToList<Person>()) 
      { 
          Console.WriteLine("{0}\t{1}\t\t{2}", p.PersonID, p.Name, p.Age); 
      } 

6. Use Linq to perform the Max, Min, Average queries.

       ///////////////////////////////////////////////////////////////////// 
       // Print the average, max, min age of the persons. 
       // 
       double avgAge = (from p in persons 
                        select p.Age).Average(); 
       Console.WriteLine("The average age of the persons is {0:f2}", avgAge); 
 
 
       double maxAge = (from p in persons 
                        select p.Age).Max(); 
       Console.WriteLine("The maximum age of the persons is {0}", maxAge); 
 
 
       double minAge = (from p in persons 
                        select p.Age).Min(); 
       Console.WriteLine("The minimum age of the persons is {0}", minAge); 

7. Use Linq to count the Person whose age is larger than 20

       ///////////////////////////////////////////////////////////////////// 
       // Count the persons who age is larger than 20 
       // 
       var query2 = from p in persons 
                    where p.Age > 20 
                    select p; 
 
 
       int count = query2.Count(); 
       Console.WriteLine("{0} persons are older than 20:", count); 
       for (int i = 0; i < count; i++) 
       { 
           Console.WriteLine(query2.ElementAt(i).Name); 
       } 

 

More Information

MSDN: LINQ to Objects
http://msdn.microsoft.com/en-us/library/bb397919.aspx

How to Query an ArrayList with LINQ
http://msdn.microsoft.com/en-us/library/bb397937.aspx