matthew phung
asked on
Help converting a helper method to an extension
Below is a helper method for converting Enums into a list for binding purposes.
The helper method works but I am having trouble converting it to an extension. My extension is below:
public static List<Item<Enum, string>> ToList<T>() where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("T must be an enumerated type");
}
return Enum.GetValues(typeof(T))
.Cast<Enum>()
.Select(value => new Item<Enum, string>
{
Description = (Attribute.GetCustomAttribute(value.GetType().GetField(value.ToString()), typeof(DescriptionAttribute)) as DescriptionAttribute).Description,
Value = value
})
.OrderBy(item => item.Description)
.ToList();
}
The helper method works but I am having trouble converting it to an extension. My extension is below:
public static List<Item<Enum, string>> ToList<T>(this T myEnum) where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("T must be an enumerated type");
}
var list = Enum.GetValues(typeof(T))
.Cast<Enum>()
.Select(value => new
{
(Attribute.GetCustomAttribute(value.GetType().GetField(value.ToString()), typeof(DescriptionAttribute)) as DescriptionAttribute).Description,
value
})
.OrderBy(item => item.Description)
.ToList();
return null;
}
public class Item<TValue, TDisplay>
{
public Item()
{
}
public Item(TValue value, TDisplay description )
{
Value = value;
Description = description ;
}
public TValue Value { get; set; }
public TDisplay Description { get; set; }
}
ASKER
The ToList function in the extension is causing the following error :
The type 'System.Linq.IOrderedEnume rable<Anon ymousType# 1>' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Common.Extensions.EnumExt ensions.To List<T>(T) '
Thank you in advance!
The type 'System.Linq.IOrderedEnume
Thank you in advance!
There is a ToList method directly accessible in the current namespace. The compiler won't go farther. If you explicitly state the generic parameters of the ToList call, it should work better. For this you need to put back the Item object creation instead of an anonymous type:
return Enum.GetValues(typeof(T))
.Cast<Enum>()
.Select(value => new Item<Enum, string>
{
Description = (Attribute.GetCustomAttribute(value.GetType().GetField(value.ToString()), typeof(DescriptionAttribute)) as DescriptionAttribute).Description,
Value = value
})
.OrderBy(item => item.Description)
.ToList<Item<Enum, string>>();
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
What problems are you having? Are you getting errors?