将char数组转换为enum数组

本文关键字:数组 enum 转换 char | 更新日期: 2023-09-27 18:28:46

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

enum CellAlignment
{
    Left = 1,
    Center = 2,
    Right = 3
}

以及用于表示5列的表的排列的字符串:CCD_ 1。有没有一种快速的方法可以使用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();

我试过了,但它说指定的强制转换无效:

CellAlignment[] cellAlignmentsX = cCellAligns.Cast<CellAlignment>().Select(foo => foo).ToArray();

谢谢!

将char数组转换为enum数组

确定:

var enumValues = text.Select(c => (CellAlignment)(c - '0'))
                     .ToArray();

假设所有值都是有效的,当然。。。它使用这样一个事实,即您可以从任何数字字符中减去"0"来获得该数字的值,并且您可以显式地从int转换为CellAlignment

使用Linq投影和Enum.Parse:

string input = "12312";
CellAlignment[] cellAlignments = input.Select(c => (CellAlignment)Enum.Parse(typeof(CellAlignment), c.ToString()))
                                      .ToArray();

您可以使用Array.ConvertAll函数,如下所示:

CellAlignment[] alignments = Array.ConvertAll("12312", x => (CellAlignment)Int32.Parse(x));

您可以使用这个:

var s = "12312";
s.Select(x => (CellAlignment)int.Parse(x.ToString()));

您可以编写一个循环

List<CellAlignment> cellAlignments = new List<CellAlignment>();
foreach( int i in iCellAlignments)
{
    cellAlignments.Add((CellAlignment)Enum.Parse(typeof(CellAlignment), i.ToString());
}

尝试类似以下内容;

int[] iCellAlignments = new int[5] { 1, 2, 3, 1, 2 };
        CellAlignment[] temp = new CellAlignment[5];

        for (int i = 0; i < iCellAlignments.Length; i++)
        {
            temp[i] =(CellAlignment)iCellAlignments[i];
        }