Our app uses a string to house character-values used to indicate enum values. for ex, the enum for aligning cells in a table:
enum CellAlignment
{
Left = 1,
Center = 2,
Right = 3
}
and the string used to represent alignments for a table of 5 columns: "12312". Is there a snappy way to use LINQ to convert this string into CellAlignment[] cellAlignments?
here’s what I’ve resorted to:
//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();
…ive tried this but it said specified cast not valid:
CellAlignment[] cellAlignmentsX = cCellAligns.Cast<CellAlignment>().Select(foo => foo).ToArray();
thank you!
Sure:
That assumes all the values are valid, of course… it uses the fact that you can subtract ‘0’ from any digit character to get the value of that digit, and that you can explicitly convert from
inttoCellAlignment.