Convert string array to enum on the fly

痞子三分冷 提交于 2019-12-01 15:49:26

Sure! This is all you need:

IEnumerable<myEnum> items = myArray.Select(a => (myEnum)Enum.Parse(typeof(myEnum), a));

You'll want to use Enum.Parse: http://msdn.microsoft.com/en-us/library/essfb559.aspx

MyProperty = (myEnum)Enum.Parse(typeof(myEnum), myArray[0]);

How you'll want to use that with your array I guess is up to your needs.

EDIT: By any chance, is it feasible to store your adapter names to your array as enumerations in the first place? Is there some reason the array must be strings?

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.

MethodMan

You do not have to use Parse if you want to get the name of the enum's value. Don't use .ToString(), use this instead. For example if I want to return Ethernet I would do the following:

public enum myEnum
{
    Ethernet,
    Wireless,
    Bluetooth
}

In your main class add this line of code:

var enumName = Enum.GetName(typeof(myEnum), 0); //Results = "Ethernet"

If you want to enumerate over the Enum Values you could do this to get the values:

foreach (myEnum enumVals in Enum.GetValues(typeof(myEnum)))
{
    Console.WriteLine(enumVals);//if you want to check the output for example
}

Use Enum.Parse in the loop for each element in the array.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!