In order to convert from a string to an enumeration in .NET you can use the method Enum.Parse as follows:
public enum SortExpressions
{
FirstNameAsc,
FirstNameDesc,
LastNameAsc,
LastNameDesc
}
var value = "lastnameasc";
var sortExpression = (SortExpressions) Enum.Parse(typeof(SortExpressions), value, true);
Since this operation is often needed we should make a ConvertToEnum method so we can reuse it. But instead of returning it as the typical object type, we should rather use generics to return it as the actual type:
/// <summary>
/// Converts a string to the specificed enumeration.
/// </summary>
public T ConvertToEnum<T>(string value, T defaultEnum)
{
value = value.Replace(" ", "").Trim();
try
{
return (T) Enum.Parse(typeof(T), value, true);
}
catch
{
return defaultEnum;
}
}
A try/catch is used instead of the method Enum.IsDefined as it’s case-sensitive.
And this is how you can use our new ConvertToEnum method:
var value = "lastnameasc";
var sortExpression = ConvertToEnum<SortExpressions>(value, SortExpressions.FirstNameAsc);
