1.2. A Simple C# 3.0 LINQ to Objects Program

Listing 1-1 is a console program snippet that uses LINQ to Objects to display a specific element in an array.

Example 1-1. Using LINQ to Objects with List<T>
List<Person> people = new List<Person> {
    new Person() { ID = 1,
                   IDRole = 1,
                   LastName = "Anderson",
                   FirstName = "Brad"},
new Person() { ID = 2,
                   IDRole = 2,
                   LastName = "Gray",
                   FirstName = "Tom"}
            };

            var query = from p in people
                        where p.ID == 1
                        select new { p.FirstName, p.LastName };

            ObjectDumper.Write(query);

In Listing 1-1 you define a collection of Person objects and insert a couple of elements. List<T> is a generic class that implements IEnumerable<T>, so it's suitable for LINQ querying.

Next you declare a variable, query, to hold the result ...

Get LINQ for Visual C# 2008 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.