我们的应用程序使用字符串来存放用于指示枚举值的字符值。例如,用于对齐表格中的单元格的枚举:
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();
谢谢你!
答案 0 :(得分:5)
不确定
var enumValues = text.Select(c => (CellAlignment)(c - '0'))
.ToArray();
假定所有值都是有效的,当然......它使用的事实是你可以从任何数字字符中减去'0'来获得该数字的值,并且你可以明确地从int
转换为CellAlignment
。
答案 1 :(得分:4)
使用Linq投影和Enum.Parse
:
string input = "12312";
CellAlignment[] cellAlignments = input.Select(c => (CellAlignment)Enum.Parse(typeof(CellAlignment), c.ToString()))
.ToArray();
答案 2 :(得分:1)
你可以使用像这样的Array.ConvertAll函数:
CellAlignment[] alignments = Array.ConvertAll("12312", x => (CellAlignment)Int32.Parse(x));
答案 3 :(得分:0)
您可以使用:
var s = "12312";
s.Select(x => (CellAlignment)int.Parse(x.ToString()));
答案 4 :(得分:0)
你可以写一个循环
List<CellAlignment> cellAlignments = new List<CellAlignment>();
foreach( int i in iCellAlignments)
{
cellAlignments.Add((CellAlignment)Enum.Parse(typeof(CellAlignment), i.ToString());
}
答案 5 :(得分: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];
}