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:

winners.Sort(
   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:

winners.ForEach(
   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.

Christian

Comments

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

The comments to this entry are closed.