Ultra Mobile PC
LINQ Part 2 - Filtering & Sorting Using Data from the Database

LINQ Part 1 - Filtering & Sorting Object Lists

Today accessing object lists, databases, and XML requires a different syntax for every of these technologies. LINQ (Language Integrated Query) makes it possible to use the same syntax accessing all of these technologies.

In this and some follow-on blog entries I'm showing how LINQ can be used to access object lists, databases, and XML.

With the sample application I have a list of racers List<Racer>. The Racer class is a very simple class that contains the name of the racer and the number of wins. With the result I just want the racers who have won more than three races, and the result should be sorted by the number of wins.

The traditional way (using .NET 2.0) to filter objects from a List<T> is by using the FindAll method passing a predicate. The predicate can be implemented using an anonymous method as shown:

List<Racer> winners = racers.FindAll(
   delegate(Racer r)
      return r.Wins > 3;

Sorting the result is done with the Sort method of List<T>. One overload of Sort accepts a generic delegate Comparison<T> that can be implemented as anonymous method:

   delegate(Racer r1, Racer r2)
      return r2.Wins.CompareTo(r1.Wins);

Displaying the resulting collection is done by using the ForEach method passing an Action<T> delegate:

   delegate(Racer r)
      Console.WriteLine("{0}, {1}", r.Name, r.Wins);

C# 2.0 with the generic list class and using anonymous methods makes the filtering and sorting very easy (as soon as you are used to the syntax for anonymous methods). It's even simpler using the LINQ query expression (C# 3.0). The same result shown before can be done with a simple from in where orderby select:

var winners = from r in racers
   where r.Wins > 3
   orderby r.Wins descending
   select r;

foreach (Racer r in winners)
   Console.WriteLine("{0}, {1}", r.Name, r.Wins);

With the next blog entries I'm showing how to do the same query using a database and XML sources, and what's behind the scenes.



Feed You can follow this conversation by subscribing to the comment feed for this post.

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.


Post a comment

Your Information

(Name and email address are required. Email address will not be displayed with the comment.)