2012-03-21 3 views
2

우리 앱은 문자열을 사용하여 열거 형 값을 나타내는 데 사용되는 문자 값을 저장합니다. 예를 들어, 테이블의 셀을 정렬하기위한 열거 :char 배열을 enum 배열로 변환 하시겠습니까?

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(); 

당신을 감사합니다!

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

답변

5

물론 :하십시오 Linq에 투사와 Enum.Parse 사용

+0

감사합니다. 이것은 매우 짧습니다. enum은 int를 기반으로하므로 명시 적으로 변환하는 것이 구문 분석하는 것보다 낫다고 생각합니다. – mdelvecchio

4

모든 값이 유효 가정

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

즉, 물론 ... 당신은 뺄 수 있다는 사실을 사용하여 해당 숫자의 값을 얻기 위해 임의의 숫자 문자에서 '0'을 가져와 int에서 CellAlignment으로 명시 적으로 변환 할 수 있습니다.

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

루프를 반복하지 않고 L/L을 수행하려고합니다. – mdelvecchio

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

루프를 반복하지 않고 L/L을 수행하려고합니다. – mdelvecchio

관련 문제