Friday, 13 July 2007

Introducing LINQ (to objects) in 10 seconds

The database uses of LINQ (to SQL/to Entities) get all of the glory, but LINQ can be used against your run of the mill objects in .NET. Take for example sorting strings;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
static void Main(string[] args)
{
  string[] friends = new string[]{
    "Tony Johnson",
    "Joe Mangel",
    "Helen Daniels",
    "Sky Mangel",
    "Stingray",
    "Dylan Timmins",
    "Gerard Rebbeci",
    "Pippa Styger"};

  IEnumerable<string> sorted = from friend in friends
          orderby friend select friend;

  foreach (string person in sorted)
    Console.WriteLine(person);
}

The interesting part is on lines 13/14 - we get a list of sorted strings by executing SQL like syntax on our string array. Lets try something else, lets sort the list based on who's got the longest name, sorting from longest to shortest: Notice I'm also using anonymous types in the following example( var ).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
static void Main(string[] args)
{
  var friends = new string[]{
    "Tony Johnson",
    "Joe Mangel",
    "Helen Daniels",
    "Sky Mangel",
    "Stingray",
    "Dylan Timmins",
    "Gerard Rebbeci",
    "Pippa Styger"};


  var sorted = from friend in friends
         orderby friend.Length descending
         select friend;

  foreach (var person in sorted)
    System.Console.WriteLine(person);
}

Easy, but very useful. You can use LINQ to sort collections of objects and do all sorts of powerful and useful things.

No comments:

Post a Comment