2012-03-21 107 views
2

我们的应用程序使用一个字符串来容纳用来指示枚举值的字符值。为前,枚举用于在表对准细胞:将char数组转换为枚举数组?

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

和用于表示比对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(); 

...香港专业教育学院试过,但它说,指定的强制转换无效:

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

谢谢!

回答

5

肯定的:

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

假定所有的值都是有效的,当然...它使用的事实,你可以减去'0'从任何数字字符获得该数字的值,并且您可以明确地从int转换为CellAlignment

+0

谢谢,这是超短的。由于枚举是基于整数,我相信显式转换比解析更好。 – mdelvecchio 2012-03-21 18:18:33

4

使用LINQ的投影和Enum.Parse

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

您可以使用此:

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

你可以写一个循环

List<CellAlignment> cellAlignments = new List<CellAlignment>(); 

foreach(int i in iCellAlignments) 
{ 
    cellAlignments.Add((CellAlignment)Enum.Parse(typeof(CellAlignment), i.ToString()); 
} 
+0

试图做w/LINQ而不是迭代循环。 – mdelvecchio 2014-05-29 15:23:34

1

你可以使用Array.ConvertAll功能是这样的:

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

尝试类似的东西下列;

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]; 
     } 
+0

试图做w/LINQ而不是迭代循环。 – mdelvecchio 2014-05-29 15:22:42