Solibulo

Uninteresting things

Useful LINQ extensions

by softlion 2. February 2009 16:13

LINQ is an intuitive and powerful extension to .NET. But it misses a useful method to be able to write code as compact as possible. Look at this code:

   1: var list = from xitem in (XDocument.Parse(xmlText).Root.FirstNode as XElement).Elements()
   2:            select new { keyText = xitem.Name.LocalName, keyValue = xitem.Value };
   3:  
   4: foreach( var keyPair in list )
   5: {
   6:     ... do some action ...
   7: }

 

What if you could write a single line instead of the foreach loop:

   1: list.Action( keyPair => s.Append(keyPair.keyText + "=" + keyPair.keyValue) );

 

Well this is now possible if having this extension method in your project:

   1: public static class LINQExtension
   2: {
   3:         public static void Action<T>(this IEnumerable<T> list, Action<T> action)
   4:         {
   5:             foreach (var t in list)
   6:                 action(t);
   7:         }
   8:  
   9:         public static string Append(this IEnumerable<string> list)
  10:         {
  11:             StringBuilder sb = new StringBuilder();
  12:             list.Action(s => sb.Append(s));
  13:             return sb.ToString();
  14:         }
  15: } 

 

Next is an example usage of these methods to compute the MD5 hash of any string:

   1: // Compute the MD5 hash of a string
   2: public string ComputeMD5Hash( string signatureContent )
   3: {
   4:       StringBuilder signature = new StringBuilder();
   5:       MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(signatureContent)).Action(b => signature.AppendFormat("{0:x2}", b));
   6:       return signature.ToString();
   7: }

Of course it is a bad example, as there is a much more efficient way to do it:

 

return BitConverter.ToString(SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(signatureContent)));

 

 

Tags: