Coding Villa

Convert enumeration to list in C#

Author : Hassan Shafiq

Share with Friends
Views : 876
Ratings : 0
Bookmarks : 0
Farourities : 0

Description


In this simple article you will learn that how we can convert enumeration to list in c#.


Advertisements


 

 

Enumeration

 

Enumeration provides the best way to define a set of named integral constants which we assigned to a variable by using the enum keyword before variable. For an instance, if we define a variable whose value will represent the name of the countries then we can declare enumeration in this way

enum CountryNames { Pakistan, Japan, Italy, Spain};

 

Enum.GetValues Method

 

The GetValues method returns the value of enumerators. If multiple enumerators have the same value, then the returned array contains duplicate values.

 

 

Syntax

 

public static Array GetValues(

            Type enumType

)

 

Enum.GetNames Method

 

 

The GetNames method retrieves an array of the names of the enumerators.

 

 

Syntax

 

public static string[] GetNames(

            Type enumType

)

 

 

Conversion

 

 

The following code will show the list of values for each member of the enumType enumeration.

 

 

Code

 

//Using GetVaues Method

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

class Program

    {

enum Days { Sat, Sun, Mon, Tue, Wed, Thu, Fri };

static void Main(string[] args)

        {

            Array arr = Enum.GetValues(typeof(Days));

            List<string> lstDays = new List<string>(arr.Length);

foreach (int i in Enum.GetValues(typeof(Days)))

Console.WriteLine(i);

Console.ReadLine();

        }

    }

 

//Using GetNames Method

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

class Program

    {

enum Days { Sat, Sun, Mon, Tue, Wed, Thu, Fri };

static void Main(string[] args)

        {

            Array arr = Enum.GetNames(typeof(Days));

            List<string> lstDays = new List<string>(arr.Length);

foreach (int i in Enum.GetNames (typeof(Days)))

Console.WriteLine(i);

Console.ReadLine();

        }

    }

 



Article Tags
Share with Friends

Comments




Leave a Reply

Name (required)  
Mail (will not be published) (required)   
 
Enter This Code
Captcha
 

Advertisements

Article Categories

.NET


Databases


Mobile Development


Operating Systems


Web Development


Coding Villa on Facebook