November 2009 Entries

So in response to some comments on my original post on this topic, I started playing around with some other ideas.  I figured it would be cleaner to post code here, rather than the comments.

How many variations on the theme can we really have?

As suggested in the comments on the previous post:

   1: public static string Join1<T>( this IEnumerable<T> items, string delimiter, Func<T,string> converter )
   2: {
   3:     return string.Join( delimiter,
   4:                         items
   5:                             .Select( converter )
   6:                             .Where( s => !string.IsNullOrEmpty( s ) )
   7:                             .ToArray() );            
   8: }

Using Aggregate Linq extension:

   1: public static string Join2<T>( this IEnumerable<T> items, string delimiter, Func<T, string> converter )
   2: {
   3:     return items
   4:         .Aggregate( string.Empty,
   5:                     ( agg, next ) =>
   6:                         {
   7:                             var sNext = converter( next );
   8:  
   9:                             return string.IsNullOrEmpty( sNext )
  10:                                        ? agg
  11:                                        : agg + delimiter + sNext;
  12:                         } );
  13: }

Aggregate again:

   1: public static string Join3<T>( this IEnumerable<T> items, string delimiter, Func<T, string> converter )
   2: {
   3:     return items
   4:         .Select( converter )
   5:         .Aggregate( ( agg, sNext ) => string.IsNullOrEmpty( sNext )
   6:                                           ? agg
   7:                                           : agg + delimiter + sNext );
   8: }

And again:

   1: public static string Join4<T>( this IEnumerable<T> items, string delimiter, Func<T, string> converter )
   2: {
   3:     return items
   4:         .Select( converter )
   5:         .Where( s => !string.IsNullOrEmpty( s ) )
   6:         .Aggregate( ( agg, next ) => agg + delimiter + next );
   7: }

In the comments for my previous post, there was a decent discussion about the performance of string aggregation, and the suggestion of using StringBuilder instead.  I’m not too concerned about it.  I’m not dealing with large data sets.

Tags: ,