Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string array to enum on the fly

I am binding an enum to a property grid like this:

public enum myEnum
{
    Ethernet,
    Wireless,
    Bluetooth
}

public class MyClass
{
    public MyClass()
    {
        MyProperty = MyEnum.Wireless;
    }

    [DefaultValue(MyEnum.Wireless)]
    public MyEnum MyProperty { get; set; }
}

public Form1()
{
    InitializeComponent();
    PropertyGrid pg = new PropertyGrid();
    pg.SelectedObject = new MyClass();
    pg.Dock = DockStyle.Fill;
    this.Controls.Add(pg);
}

My problem: I get data on the fly when the program is running. I read the network adapter then store adapter names to myArray like this:

string[] myArray = new string[] { };
myArray[0] = "Ethernet";
myArray[1] = "Wireless";
myArray[2] = "Bluetooth";

Is possible convert myArray to myEnum on the fly using c#? Thank You.

like image 699
new bie Avatar asked Dec 12 '12 14:12

new bie


2 Answers

Sure! This is all you need:

IEnumerable<myEnum> items = myArray.Select(a => (myEnum)Enum.Parse(typeof(myEnum), a));
like image 65
Joshua Avatar answered Oct 12 '22 01:10

Joshua


If your source data is not something entirely reliable, you may want to consider converting only the items that can actually be parsed, using TryParse() and IsDefined().

Getting an array of myEnums from an array of strings can be performed by the following code:

myEnum [] myEnums = myArray
    .Where(c => Enum.IsDefined(typeof(myEnum), c))
    .Select(c => (myEnum)Enum.Parse(typeof(myEnum), c))
    .ToArray();

Note that IsDefined() only works with a single enumerated value. If you have a [Flags] enum, combinations fail the test.

like image 4
Suncat2000 Avatar answered Oct 11 '22 23:10

Suncat2000