I know I’m a little late to the party, but I am quickly falling in love with Linq. Once you start adopting its functional mindset, it is so expressive and direct.
I once heard someone way that once you really get Linq, you’ll won’t ever need to write a For/Each loop again. Probably an overstatement, but still I was intrigued. I set out last night to see how Linq could negate the need for For/Each.
I set out to find a way to create ADO.NET connection strings. In the past, I would have probably used foreach to iterate over a collection using StringBuilder and String.Format to build up the connection string. I dispensed with all that old-school thought and created the connection string as shown below in Figure 1. As a bonus, I also learned (thanks to a little prompting from Resharper) a shortcut for initializing a collection.
The Linq code in lines 10 and 11 is where the cool stuff happens. Each element from the dictionary is selected to create a value pair and the Linq Aggregate() operator is used to concatenate all of the value pairs. All very sweet!
1var o = new Dictionary< string, string >()
2 {
3 { "Data Source", "DUFFSQLSERVER2008" },
4 { "Initial Catalog", "Chinook" },
5 { "Persist Security Info", "True" },
6 { "User ID", "xxxxx" },
7 { "Password", "xxxxx" }
8 };
9
10var ConnectionString = o.Select( i => i.Key + "=" + i.Value ).
11 Aggregate( ( a, b ) => a + ";" + b );
12
13Console.WriteLine( ConnectionString );
I used LinqPad to create and test this code. I just started using LinqPad and can’t believe I ever coded without it. Beyond being a great test bed for Linq, it is a superb snippet compiler. LinqPad is a free download and should be in every coder’s toolbox.



