How to convert enum to int array in C#

In this post, we will learn how to convert enum to int array in C#. The Enum or Enumeration is “An enumeration or enum is a set of named constants of the underlying integral numeric type. To define an enumeration type, use the enum keyword and specify the names of enum members.

1. How to convert enum to int array in C#


The Enum.GetValues() returns an array of enum constant values and The Array.ConvertAll() method is used to convert an array of one type to another type, here converting an array of enum to int. For each loop is used to iterate over the array and display its values.

using System;
public class Program {
enum Animals
      {
         Lion= 1,
         Tiger = 2,
         Zebra = 3,
         Zarif = 4,
         Ele =5,
         Cat =6
         
      }
public static void Main() 
{

//int[] arr = Array.ConvertAll((int[])Enum.GetValues(typeof(Animals)), Convert.ToInt32);
int[] result = Array.ConvertAll(Animals), value => (int) value); 
foreach(int ele in arr)
{
         Console.WriteLine(ele);
}


   }
}

Output

1
2
3
4
5
6

2. How to convert enum to int array in C#


In this C# example, The Enum.GetValues() returns an array of enum constants values and to get IEnumerable<T> of all values the cast<T> is used on the array. we are displaying the values of the array using for-each loop.

using System;
using System.Linq;
using System.Collections.Generic;
public class Program {
enum Animals
      {
         Lion= 1,
         Tiger = 2,
         Zebra = 3,
         Zarif = 4,
         Ele =5,
         Cat =6
         
      }
public static void Main() 
{
var arr = Enum.GetValues(typeof(Animals)).Cast<Animals>().Select(e => (int)e);

//Console.WriteLine(String.Join(Environment.NewLine, arr));
foreach(var ele in arr)
{
         Console.WriteLine(ele);
}


   }
}

Output

1
2
3
4
5
6

3. How to convert enum to int list in C#


In this C# example, We are converting enum constant values to array The Enum.GetValues() is returns an array of enum constants values and to get IEnumerable<T> of all values the cast<T> is used on the array and converted the array to a list using tolist() method. We display the values of an array using for-each loop.

using System;
using System.Linq;
using System.Collections.Generic;
public class Program {
enum Animals
      {
         Lion= 1,
         Tiger = 2,
         Zebra = 3,
         Zarif = 4,
         Ele =5,
         Cat =6
         
      }
public static void Main() 
{
var mylist = Enum.GetValues(typeof(Animals)).Cast<Animals>().Select(e => (int)e).ToList();             

foreach(var ele in mylist)
{
         Console.WriteLine(ele);
}


   }
}

OUtput

1
2
3
4
5
6