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.
Sure! This is all you need:
IEnumerable<myEnum> items = myArray.Select(a => (myEnum)Enum.Parse(typeof(myEnum), a));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With