LINQ Epiphany

LINQ is old news, but I recently started using Visual Studio 2008 and had the LINQ Epiphany. I’m working on an application to do some automation work with iTunes. I was writing a method and it occurred to me using LINQ I could cut things down.

Old way:

1
2
3
4
5
6
7
8
9
List<iTunesTrack> orphanTracks = new List<iTunesTrack>();
foreach (iTunesTrack track in AllTracks)
{
  if (track.Location == null || !(File.Exists(track.Location)))
  {
     orphanTracks.Add(track);
  }
}
return orphanTracks;

New way:

1
2
3
4
5
var orphanTracks =
        from track in AllTracks
        where track.Location == null || !(File.Exists(track.Location))
        select track;
return orphanTracks;

I don’t have the sample i front of me, but I also found the Except clause came in great handy when I wanted to compare two lists and just get the items that occur in only the first list. Microsoft’s 101 LINQ Samples got me started in no time.

One final thing of note about the new example is the var keyword. The fact I can say var x = Object(); is pretty amazing. The fact this is strongly typed is even more amazing. The most impressive thing is at design time, Visual Studio STILL gives me intellisense on these variables. The one downside is, without comments, it’s no longer obvious what kind of objects the code is working on. When another developer is reviewing or I come back in 6 months, this could be problematic.

This entry was posted in General and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *