21 Oct 2010 @ 10:15 AM 

Here are a couple real handy enum exntensions to have around. This first one returns all the vaues of the enum in a list. This is perfect for generating dropdown lists or selections. The important aspect to note here is that the list will always contain the latest additions to the enum. So you don’t have to go back and rewrite your dropdowns for the enum, it does it for you.

public static IEnumerable<T> GetEnumValues<T>(this Enum obj)
{
        IList<T> values = new List<T>();
        foreach (var val in Enum.GetValues(typeof(T)).Cast<T>())
        {
                values.Add(val);
        }
        return values;
}

This next one turns the enum value into a more readable form. Automatically parsing out camel casing into spaces. This particular regex statement requires a preceeding and following lower case letter to space. The regex is followed by simple extension methods, for both string replacement and enum replacement.

private const string RegExEnglishPattern = "(?<!^)([A-Z][a-z]|(?<=[a-z])[A-Z])";

/// <summary>
/// Correctly spaces the enumeration value to make it english-like.
/// </summary>
/// <param name="e">The enumeration.</param>
/// <returns>The english-like form of the enumeration value.</returns>
public static string ToEnglish(this Enum e)
{
        return Regex.Replace(e.ToString(), RegExEnglishPattern, " $1");
}

public static string ToEnglish(this string value)
{
        return Regex.Replace(value, RegExEnglishPattern, " $1", RegexOptions.Compiled).Trim();
}
Posted By: boyd21
Last Edit: 14 Apr 2011 @ 09:54 PM

EmailPermalink
Tags
Tags: , , ,
Categories: .Net, Programming


 

Responses to this post » (None)

 
Tags
Comment Meta:
RSS Feed for comments

 Last 50 Posts
Change Theme...
  • Users » 3
  • Posts/Pages » 30
  • Comments » 0
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight

GeekPub



    No Child Pages.