0 Comments

A couple of quick extension methods for your amusement that I use a lot.

 

   1:          /// <summary>
   2:          /// Runs action against the specified source.
   3:          /// </summary>
   4:          /// <typeparam name="T">The type of the element.</typeparam>
   5:          /// <param name="source">The source.</param>
   6:          /// <param name="action">The action.</param>
   7:          public static void Run<T>(this IEnumerable<T> source, Function<T> action)
   8:          {
   9:              if (source == null)
  10:              {
  11:                  throw new ArgumentNullException("source");
  12:              }
  13:   
  14:              if (action == null)
  15:              {
  16:                  throw new ArgumentNullException("action");
  17:              }
  18:   
  19:              foreach (var element in source)
  20:              {
  21:                  action(element);
  22:              }
  23:          }
  24:   
  25:          /// <summary>
  26:          /// Does action against the specified source and returns the source.
  27:          /// </summary>
  28:          /// <typeparam name="T">The type of the element.</typeparam>
  29:          /// <param name="source">The source.</param>
  30:          /// <param name="action">The action.</param>
  31:          /// <returns>The source after the action is executed.</returns>
  32:          public static IEnumerable<T> Do<T>(this IEnumerable<T> source, Function<T> action)
  33:          {
  34:              if (source == null)
  35:              {
  36:                  throw new ArgumentNullException("source");
  37:              }
  38:   
  39:              if (action == null)
  40:              {
  41:                  throw new ArgumentNullException("action");
  42:              }
  43:   
  44:              return source.Select(
  45:                  element =>
  46:                  {
  47:                      action(element);
  48:                      return element;
  49:                  });
  50:          }