A Little LINQ

LINQ is out in strength and I've got to admit, even though I talked to Anders Hejlsberg over three years ago about it, I've just recently started using it in my own code.  There's a lot out on the net about it, but here's my 2c to help people get started.

 Console.WriteLine("MS-DOS 6.21".Sum(a => (int)a));

LINQ has led to many great language improvements, such as anonymous types, XLINQ, lambda expressions, extension methods, etc.  I rarely use SQL, but I love the productivity of using LINQ on everyday arrays and lists.

 foreach (string file in Directory.GetFiles(@"C:\Windows").Where(
  a => (new FileInfo(a).Attributes & FileAttributes.Hidden) != 0).OrderBy(
  a => a).Select(a => Path.GetFileName(a))) Console.WriteLine(file);

(show me all the files in C:\Windows that are hidden, sort by name, and don't include the directory)

Got an array or a generic list?  Just look at all those great new methods on them!  And it's so easy to cast an array or ArrayList into a generic list now, just use .Cast<T> and going back to an array is easy too, .ToArray();

You can do amazing stuff from 'one line' of code that would've taken 10, 20, 30 lines of code.  Some one-liners I've done recently are build entire XML documents, popular MRU lists, serialize object maps to a single file to persist settings, and many little tasks with the additional methods LINQ provides on normal IEnumerable<T> objects.  I haven't gotten into anonymous types, implicitly typed local variables (var), or query expressions sytax (var p = from c in customers...), I've only used the extension methods ('dot notation') so far.  There's plenty more to dig into, like this...

 var xml = new XElement("procs", from proc in System.Diagnostics.Process.GetProcesses()
  where proc.ProcessName != "" select new XElement("proc", new XElement("name",
  proc.ProcessName), from System.Diagnostics.ProcessThread t in proc.Threads
  orderby t.CurrentPriority select new XElement("thread",
  new XAttribute("priority", t.CurrentPriority))));  

(creates an XML document with info on the threads for the current processes running)

One of my favorite things to do is grab a Virtual PC image, drop C# Express 2008 in it, and play around with LINQ.  Or you can get a premade VPC Image with Visual Studio Team System 2008 Beta2.  I'll be giving some presentations on LINQ to my alma mater (Texas A&M University) next week using C# Express 2008.

Update (9/23/07): I recently gave some presentations on how LINQ applies to everyday objects, SQL, and XML using examples of how we access data today for each of these three areas, and how LINQ makes our life better.  Here is that code: LINQ Code.zip