Click here to Skip to main content
14,870,739 members
Please Sign up or sign in to vote.
1.86/5 (4 votes)
See more:
i need a straight solution for converting array of strings to enum
i tried alot of solutions but no result
Posted
Comments
Pheonyx 6-May-14 6:30am
   
What have you tried, what issues have you had?
oliver grace 6-May-14 6:31am
   
show your code to us.
Maciej Los 6-May-14 6:50am
   
Have you tried: Enum.Parse[^]

Try:
C#
enum myEnum
    {
    One, Two, Three
    }
private void myButton_Click(object sender, EventArgs e)
    {
    string[] inputs = new string[] { "One", "Two", "Three" };
    myEnum[] outputs = inputs.Select(i => (myEnum) Enum.Parse(typeof(myEnum), i)).ToArray();
    ...
   
I'm probably not getting the question but I'm going to have a stab at this anyway.

To convert from a String to a enum the Enum.Parse method can be used (or if you want to be fault tolerant the Enum.TryParse).

By using Linq it's easy to convert all Strings in one array to enum in the other, like in this example;
C#
using System;
using System.Linq;

namespace Sample {
    enum Fruits {
        Banana,
        Apple,
        Orange,
        Pineapple
    }

    class Program {
        static void Main(string[] args) {
            var fruitStrings = new[] {"Banana", "Apple", "Pineapple", "Orange"};
            var fruits = fruitStrings.Select(fs => (Fruits)Enum.Parse(typeof (Fruits), fs));
            Console.WriteLine("Strings: {0}", String.Join(", ", fruitStrings));
            Console.WriteLine("Enums  : {0}", String.Join(", ", fruits));
        }
    }
}

Hope this helps,
Fredrik Bornander
   
Try this:

C#
public class Problem001
{
    private enum Fruits
    {
        Banana,
        Apple,
        Orange,
        Pineapple
    }

    public Problem001()
    {
        string[] names = Enum.GetNames(typeof(Fruits));                                    
        for (int iIndex = 0; iIndex < names.Length; iIndex++)                             
        {
            Console.WriteLine(names[iIndex]);                                               
        }
    }
}
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900