Monday, May 18, 2009

Try to do this without LINQ

Today, me and my colleague Cor have been busy pair-programming for most of the day. While doing that we tried to build a dictionary which value is an enumerable collection. I think we found a great example of the power of LINQ that I think is worth sharing.

Consider the class diagram below. ExamSeries represents a examination series consisting of one or more questions. Each series has a language-specific part represented by SeriesDetail. Our goal was to be able to apply a Specification object to a collection of ExamSeries and receive a dictionary of all series matching that specification, including the specific languages. So our intention was to get a IDictionary<ExamSeries, IEnumerable<Language>>.


We started hand-writing multiple foreach loops and managed to get what we wanted, but somehow, I got this annoying feeling in the back of my head that this should be easier. After a lot of experimenting, we found the following rather nice example of using LINQ.


Not bad eh?