0

I'm trying to make a generic method from this method:

public static SelectList LanguagesToSelectList()
{
   return new SelectList(
        Enum.GetValues(typeof(Languages))
        .Cast<Languages>()
        .Select(g => new KeyValuePair<Languages, string>(
            g,
            Resources.Views_GamesAndApplications.ResourceManager.GetString("Language_" + g.ToString()
            )
        )), 
        "Key", 
        "Value"
        );
}  

Here's what I got:

public static SelectList ToSelectList(Enum enumType, ResourceManager resourceManager, string resourcePrefix)
{
    return new SelectList(
        Enum.GetValues(typeof(enumType))
        .Cast<enumType>()
        .Select(g => new KeyValuePair<enumType, string>(
            g,
            resourceManager.GetString(resourcePrefix + g.ToString())
            )), 
        "Key", 
        "Value");
} 

However, enumType shouldn't be of type Enum (nor should it be of type Type), and I can't figure out of what type is SHOULD be, or if I should rephrase the entire method..

Usage example (compliant with given answer):

@Html.DropDownListFor(
    m => m.Language,  
    SelectListHelper.ToSelectList<Languages>   
      (Resources.Views_GamesAndApplications.ResourceManager,"Language_"))

Thanks.

Oren A
  • 5,870
  • 6
  • 43
  • 64

1 Answers1

3
public static SelectList ToSelectList<T>(ResourceManager resourceManager, string resourcePrefix)
    where T : struct 
{
    return new SelectList(Enum.GetValues(typeof(T)).Cast<T>()
                .Select(g => new KeyValuePair<T, string>(g, resourceManager.GetString(resourcePrefix + g.ToString()))), "Key", "Value");
}  

//Example:
var list = ToSelectList<Languages>(someResourceManager, "somePrefix");
SeeSharp
  • 1,730
  • 11
  • 31
  • 2
    Maybe you can add a small example about how you can call this method? That said, you should add a [constraint to ensure T is an enum](http://stackoverflow.com/a/1409873/588868). – Steve B Feb 03 '13 at 08:01
  • You need to return the created list (I know the asker forgot that as well). I don't know why they don't make a generic version of `Enum.GetValues`. Instead of `.Cast()` you can also say `((T[])Enum.GetValues(typeof(T)))` (or in this case just unbox when you create the `KeyValuePair<,>`). – Jeppe Stig Nielsen Feb 03 '13 at 08:13