将char数组转换为枚举数组?

mde*_*hio 2 c# linq

我们的应用程序使用字符串来存放用于指示枚举值的字符值.例如,用于对齐表格中的单元格的枚举:

enum CellAlignment
{
    Left = 1,
    Center = 2,
    Right = 3
}
Run Code Online (Sandbox Code Playgroud)

和用于表示5列表的对齐的字符串:"12312".是否有一种快速的方法来使用LINQ将此字符串转换为CellAlignment[] cellAlignments

这就是我所使用的:

//convert string into character array
char[] cCellAligns = "12312".ToCharArray();

int itemCount = cCellAligns.Count();

int[] iCellAlignments = new int[itemCount];

//loop thru char array to populate corresponding int array
int i;
for (i = 0; i <= itemCount - 1; i++)
    iCellAlignments[i] = Int32.Parse(cCellAligns[i].ToString());

//convert int array to enum array
CellAlignment[] cellAlignments = iCellAlignments.Cast<CellAlignment>().Select(foo => foo).ToArray();
Run Code Online (Sandbox Code Playgroud)

...我试过这个,但它说指定的演员无效:

CellAlignment[] cellAlignmentsX = cCellAligns.Cast<CellAlignment>().Select(foo => foo).ToArray();
Run Code Online (Sandbox Code Playgroud)

谢谢!

Jon*_*eet 5

当然:

var enumValues = text.Select(c => (CellAlignment)(c - '0'))
                     .ToArray();
Run Code Online (Sandbox Code Playgroud)

假设所有的值都是有效的,当然......它使用的事实是你可以从任何数字字符中减去'0'来获得该数字的值,并且你可以显式转换intCellAlignment.