IMG-LOGO

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

andy - 22 Mar, 2014 25226 Views 4 Comment

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
22 Mar, 2017
Nice code. But the method GetEnumList was marked as void and you are returning list.
andy
29 Mar, 2017
thank you for pointing this out. I actually didnt test in the code directly. Just remove the word void ;-)
Nupur
16 Jul, 2018
Hey thank you so much, your code totally solved my problem! thanks again!!
Larry
09 Feb, 2020
Awesome! Exactly what i was looking for! Thank you!!
Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Articles

How to remove html tags from string in c#?

Sometimes you need to remove HTML tags from string to ensure there are no dangerous or malicious scripts especially when you want to store the string or data text into the database.