The power of extension methods

by Oliver 21. May 2010 18:59

Manchmal stolpere ich über alten Code, den einer von uns irgendwann mal geschrieben hat, und denke mir: Wow! Vorher muss ich aber erstmal lesen, was er macht:

   1: public string GetEquipmentStrings()
   2: {
   3:     var first = true;
   4:     var strBuilder = new StringBuilder();
   5:  
   6:     foreach (var value in Enum.GetValues(typeof(CampsiteEquipmentType)))
   7:     {
   8:         var eqVal = (CampsiteEquipmentType) value;
   9:  
  10:         if (EquipmentValues[eqVal] == true)
  11:         {
  12:             var strVal = EquipmentStrings[eqVal];
  13:  
  14:             if (!string.IsNullOrEmpty(strVal))
  15:             {
  16:                 if (!first)
  17:                     strBuilder.Append(", ");
  18:  
  19:                 strBuilder.Append(strVal);
  20:  
  21:                 first = false;
  22:             }
  23:         }
  24:     }
  25:  
  26:     return strBuilder.ToString();
  27: }

Er verkettet eine Menge von Strings und fügt zwischen ihnen jeweils ein Komma und ein Leerzeichen ein. Das Ganze bekommt man aber auch kürzer und vor allem übersichtlicher hin:

   1: public string GetEquipmentStrings()
   2: {
   3:     var locationValues = Enum<CampsiteEquipmentType>.GetValues().ToList();
   4:  
   5:     return EquipmentStrings
   6:         .Where(pair => locationValues.Contains(pair.Key) && !string.IsNullOrEmpty(pair.Value))
   7:         .Select(pair => pair.Value).ToList()
   8:         .JoinNonEmpty(", ");
   9: }

Zugegebenermaßen passiert hier einiges unter der Haube, aber das muss man an dieser Stelle ja nicht sehen. Spannend sind zwei Dinge:

  1. Die Enum<T>-Klasse, die bei GetValues direkt eine Liste von enum-Werten zurückgibt.
  2. Die Methode JoinNonEmpty(), die die Verkettung von Strings mit einem frei wählbaren Trennstring übernimmt. Hier die Implementation:
   1: public static string JoinNonEmpty(this List<string> values, string separator)
   2: {
   3:     values.RemoveAll(s => string.IsNullOrEmpty(s));
   4:     return String.Join(separator, values.ToArray());
   5: }

Das war’s schon. So macht coden Spaß!

Oliver

enjoyed the post?

Tags:

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

About Oliver

shades-of-orange.com code blog logo I build web applications using ASP.NET and have a passion for javascript. Enjoy MVC 4 and Orchard CMS, and I do TDD whenever I can. I like clean code. Love to spend time with my wife and our children. My profile on Stack Exchange, a network of free, community-driven Q&A sites

About Anton

shades-of-orange.com code blog logo I'm a software developer at teamaton. I code in C# and work with MVC, Orchard, SpecFlow, Coypu and NHibernate. I enjoy beach volleyball, board games and Coke.