Geeks With Blogs
Jamie Kurtz Promoting architectural simplicty

There's a log of focus with LINQ on interacting with databases, but the other day I was playing around and found other great uses for it. In fact, none of the following examples are related to databases at all.

For example, you can use LINQ to filter and sort an array of integers:

int[] numbers = { 10, 25, 30, 52, 64, 86, 97 };
var myList = from number in numbers where (number % 2 == 0) select Convert.ToString(number) + " is even";
foreach (string s in myList)

Note that we are finding only even numbers, and then building a little string to return - kind of like something in a SQL Server T-SQL statement.

This next example illustrates how we can query the local machine for all services that are running, and then sort them by Service Name:

var services = from service in ServiceController.GetServices()
               where service.Status == ServiceControllerStatus.Running
               orderby service.ServiceName
               select service;

I think one of the incredible capabilities showcased by this example is the ability to use the .NET object model for building "queries". You can see how the WHERE clause checks the Status property of each ServiceControl instance - comparing it to the ServiceControllerStatus enumerator. Further, the SELECT clause shows that we are getting back a list of ServiceController objects - not just a list of service names.

My third and final example shows how to grab a list of file names from a local directory, filtering by the files' modified dates, and ordering by their name:

var files = from file in Directory.GetFiles(@"c:\temp")
            where File.GetLastWriteTime(file) > DateTime.Now.AddDays(-5)
            orderby file
            select file;

Now clearly all three of these scenarios could have been coded without LINQ, but I was pretty excited to see that you can combine the three main components of almost any data/info interrogation:

  1. Retrieval of the information
  2. Filtering for the information you want
  3. Sorting the information

And to accomplish all this with strongly-typed intellisense'd .NET types... simply amazing in my book!!

Posted on Saturday, December 1, 2007 8:56 PM | Back to top

Comments on this post: Cool things with LINQ in Visual Studio 2008 / .NET 3.5

# re: Cool things with LINQ in Visual Studio 2008 / .NET 3.5
Requesting Gravatar...
Great tips; well-written and real-world useful! LINQ is revolutionizing how we code!

Left by Erik Bertrand on Apr 21, 2008 9:36 AM

Your comment:
 (will show your gravatar)

Copyright © Jamie Kurtz | Powered by: