Monday, July 20, 2009

Hooked On Linq

For those that don't know what Linq is, read this:
LINQ is a set of extensions to the .NET Framework that encompass language-integrated query, set, and transform operations. It extends C# and Visual Basic with native language syntax for queries and provides class libraries to take advantage of these capabilities. - http://msdn.microsoft.com/en-us/netframework/aa904594.aspx

I've only mentioned it on my blog once a very long time ago, while I was attending CodeMash.

Well, I've been using it for a few months now (steady) and it's taken some time for me to really get used to it. I still find myself writing loops to find things inside lists, or else converting them to List so that I can use the Find() and Convert() functions freely. I've now convinced myself that Linq is my friend and I'm finally a huge fan of it. I've always been reluctant to Linq in my project because I felt like I was no longer "in control" of my collections and it added too much overhead.

Today, I found myself updating an old collection class with some new functionality and was able to shrink many of my methods down drastically using a single Linq query. In my case, I have a single collection class that offers multiple functions for extracting a subset of objects. For example, I might want to pass a parameter and only return a all objects whose member happens to match that parameter. Here is an example of one of the functions that I changed in my code to make it more readable:
public IEnumerable<PanelDefinition> FindByType(PanelType panelType)
{
foreach(var panel in this)
{
if (panel.Type == panelType)
{
yield return panel;
}
}
}
And I was able to rewrite it to this:
public IEnumerable<PanelDefinition> FindByType(PanelType panelType)
{
return from panel in this
where panel.Type == panelType
select panel;
}
To a non-geek, both snippets are very cryptic, I'm sure. However, to a geek (like myself) the bottom snippet is more "human readable"... or at least that's what we've been told anyway. :) Regardless, the second snippet has no squiggles or syntax rules to follow. Something else that's nice about the second snippet is that it's able to take advantage of all the framework niceties. I could go on and on about how cool and flexible Linq is, but go see for yourself if you're curious: http://msdn.microsoft.com/en-us/data/cc299380.aspx

1 comment:

Mark Carroll said...

Hey Luc
Here's hoping summer is going well and that the legs are bouncing back. have you heard that they are having a 50 miler (and a 50k, marathon, and 100 miler) at Pinckney? Thats where the Michigan Trail Marathon was. Its Sept. 19. I'm just saying.....: )