I have the following code:
var values1 = (EReferenceKey[])Enum.GetValues(typeof(EReferenceKey));
var valuesWithNames = values1.Select(
value => new {
Value = ((int)value).ToString("00"),
Text = Regex.Replace(value.ToString(), "([A-Z])", " $1").Trim()
});
Here’s some code that was suggested on stackoverflow that can make this method generic:
public static IEnumerable<KeyValuePair<string, string>> GetValues2<T>() where T : struct {
var t = typeof(T);
if (!t.IsEnum)
throw new ArgumentException("Not an enum type");
return Enum.GetValues(t)
.Cast<T>()
.Select(x => new KeyValuePair<string, string>(
((int)Enum.ToObject(t, x)).ToString("00"),
Regex.Replace(x.ToString(), "([A-Z])", " $1").Trim()
));
}
It gives me almost the same result but it’s missing the naming “Value” and “Text”. Can someone suggest to me how I could modify the latter code to add these and still have the results come back in order?
I did try doing it myself but it gave me errors when I tried to add in the “Value =” and “Text =” to the select of the generic:
Error 6 The name ‘Value’ does not exist in the current context
You need to define a class, values of which wiil be returned:
And modify like this: