Wednesday, Oct 27, 2010, 6:42 PM in Tools
LINQ Has Changed Me
In the old days, the post-colonial, pre-LINQ days of yore, I’d have written a one-way MD5 encryption like so:
static string GetMD5String(string s) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] hash = md5.ComputeHash(Encoding.ASCII.GetBytes(s)); StringBuilder sb = new StringBuilder(); foreach( byte b in hash ) sb.AppendFormat("{0:x2}", b); return sb.ToString(); }
This implementation is fine and has served me well for 10 years (I pulled it out of the first .NET project I ever really did). However, after using LINQ for so long, it’s hard not to see every problem as an operation over sets:
static string GetMD5String(string s) { return (new MD5CryptoServiceProvider()). ComputeHash(Encoding.Unicode.GetBytes(s)). Aggregate(new StringBuilder(), (working, b) => working.AppendFormat("{0:x2}", b)). ToString(); }
I can’t say that the LINQ version is any better, but it felt better. However, you’ll notice that I’m not using any of the LINQ keywords, e.g. “select”, “where”, etc. I find that I don’t really use them that much. It’s too jarring to mix them, e.g. “(from f in foos select f).Take(3)”, since not everything has a LINQ keyword equivalent. I tend to do “LINQ-less LINQ” more often then not.
P.S. I assume someone will be able to tell me how I can do it better. : )
P.P.S. I’m using the Insert Code for Windows Live Writer add-in. I love WLW!
11 comments
on this post
Jon Skeet:
return string.Join("", ComputeHash(Encoding.Unicode.GetBytes(s))
.Select(b => b.ToString("x2")));
Wednesday, Oct 27, 2010, 11:08 PM
RichB:
return Convert.ToBase64String(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(s)));
Wednesday, Oct 27, 2010, 11:42 PM
kenny:
static string GetMD5String( static string s)
Thursday, Oct 28, 2010, 5:33 AM
Chris Sells:
Rich, I like the Base64 version, too. That would be better than looping.
Kenny, I'm not a fan of custom extension methods in general unless I'm doing the fluent functional LINQ thing. I guess it's an unfair bias.
Thursday, Oct 28, 2010, 6:49 AM
justin chase:
Thursday, Oct 28, 2010, 7:47 AM
John Vottero:
return BitConverter.ToString(hash).Replace('-', ':');
Friday, Oct 29, 2010, 8:30 AM
Sriram Krishnan:
I often find myself writing fluent code, inserting temporary variables when I want to debug and removing them back again. : )
Sunday, Oct 31, 2010, 10:55 AM
Chris Sells:
Sunday, Oct 31, 2010, 10:56 AM
christophep:
I hate LINQ.
It is slow and it's for liquor salesman guys.
regards,
christophep | WIN32/64 Visual C++ Guy
christophepichaud@hotmail.com
Friday, Nov 12, 2010, 2:43 AM
Website Markup checker:
It says more than you think about the effort of their coding
result: HTML
413 errors
13 warnings
Thursday, Nov 18, 2010, 7:20 AM
Chris Sells:
Thursday, Nov 18, 2010, 8:04 AM



