2

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!

6 Answers 6

5

Sure:

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

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 int to CellAlignment.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, this is super short. since the enum is based on ints, i believe converting explicitly is better than parsing.
4

Using a Linq projection and Enum.Parse:

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

Comments

1

You could use Array.ConvertAll function something like this:

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

Comments

0

You can use this:

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

Comments

0

You can write a loop

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

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

1 Comment

trying to do w/ LINQ and not iterating loops.
0

Try something similar to the following;

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

1 Comment

trying to do w/ LINQ and not iterating loops.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.