Published on: 22 March, 2014

Convert Enum values into List of Key Pairs value in ASP.Net C#

Posted by andy | 6472 views 0 likes 0 favourites 2 comments
Tumblr Digg Google Plus

In this tutorial you will learn how you can create a quick function to return a list of key pairs value based on given enum type.

Let's say we have the following enum type.

public enum EnumPaymentMethod {
    CREDITCARD = 1,
    PAYPAL = 2,
    BANKDEPOSIT = 3,
    CASHONDELIVERY = 4,
    CHEQUE = 5, 
    PICKUP = 6,
    PHONE = 7
}

We will need to create a function that will accept any object of enum type and return as list of key pairs value.

public List<KeyValuePair<string, int>> GetEnumList<T>() {
    var list = new List<KeyValuePair<string, int>>();
    foreach (var e in Enum.GetValues(typeof(T))) {
        list.Add(new KeyValuePair<string, int>(e.ToString(), (int)e));
    }
    return list;
}

To use above function is pretty simple what you have to do is to pass the enum object into the function.

List<KeyValuePair<string, int>> list = GetEnumList<EnumPaymentMethod>();
Comments
kalyan
Commented on: 22 Mar, 2017 05:13:58 PM
Nice code. But the method GetEnumList was marked as void and you are returning list.
andy
Commented on: 29 Mar, 2017 02:48:20 PM
thank you for pointing this out. I actually didnt test in the code directly. Just remove the word void ;-)
Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.
Related Articles
Published on: 13 February, 2017
One thing to remember when publishing your ASP.Net web applications, you may find out, some files could be not completely published due to the settings on the file properties. One example that I had are some font types file. In order to fix this problem you can navigate to the files that are missing and right click the properties.
Published on: 11 May, 2016
The slidingExpiration attribute is used in ASP.Net form authentication. This property is used to reset the expiration time for a valid authentication cookie if a request that has already being made has passed the timeout interval. Which means, if it is already expires, the current user will require to re-authentication again.
Related Tutorials