2011-04-12 3 views
0

사전에 열거하고 그 형식 다음에 사전의 각 이름 (값)을 변환해야합니다. 나는 이런 식으로 뭔가해야 할 그 후사전에 열거하고 각 이름을 형식화하십시오.

public static Dictionary<int, string> EnumToDictionary<TK>(Func<TK, string > func) 
     { 
     if (typeof(TK).BaseType != typeof(Enum)) 
       throw new InvalidCastException(); 


      return Enum.GetValues(
       typeof(TK)) 
       .Cast<Int32>() 
       .ToDictionary(
         currentItem => currentItem => Enum.GetName(typeof(TK), currentItem)) 
       /*. func for each name */; 
      } 



     public enum Types { 

      type1 = 0, 
      type2 = 1, 
      type3 = 2 
     } 


     public string FormatName(Types t) { 
      switch (t) { 
         case Types.type1: 
           return "mytype1"; 

         case Types.type2: 
           return "mytype2"; 

         case Types.type3: 
           return "mytype3"; 

          default: 
           return string.Empty; 
       } 
      } 

:

var resultedAndFormatedDictionary = 
EnumToDictionary<Types>(/*delegate FormatName() for each element of dictionary() */); 

을 어떻게 정의하고 사전의 각 값에 대한 몇 가지 작업을 수행 위임 (Func<object, string > func)를 구현합니까?

UPDATE : Correspoding 결과는 int로서 열거 값이 키와 그것에 대한 어떤 형식의 이름을 열거에서 사전을 만들기 위해 달성하고자하는 질문에서 추측

var a = EnumToDictionary<Types>(FormatName); 

    //a[0] == "mytype1" 
    //a[1] == "mytype2" 
    //a[2] == "mytype3" 
+0

당신이 작은이 코드를 포맷 할 수 있습니다? –

+4

질문 할 수도 있습니까? 귀하의 전체 게시물은 지금까지의 진술 일뿐입니다. 뭐가 문제 야? – ChrisWue

+0

그리고 몇 가지 샘플 입력 데이터와 해당 결과를 제공하십시오 –

답변

1

되는 값입니다 , 권리?

음, 먼저 전달하는 함수는 인수로 TK을 가져야합니다. 그렇지 않습니까?
둘째, InvalidCastException을 던지면 약간 이상하게 보입니다. InvalidOperationException 더 적합 할 수 있습니다
셋째 ToDictionary 매우 가까운 이미 (또한 this question 참조) :

이제
public static Dictionary<int, string> EnumToDictionary<TK>(Func<TK, string> func) 
{ 
    if (typeof(TK).BaseType != typeof(Enum)) 
     throw new InvalidOperationException("Type must be enum"); 

    return Enum.GetValues(typeof(TK)).Cast<TK>().ToDictionary(x => Convert.ToInt32(x), x => func(x)); 
} 

이처럼 호출 할 수

public enum Types 
{ 
    type1 = 0, 
    type2 = 1, 
    type3 = 2 
} 

public string FormatName(Types t) 
{ 
    switch (t) 
    { 
     case Types.type1: 
      return "mytype1"; 

     case Types.type2: 
      return "mytype2"; 

     case Types.type3: 
      return "mytype3"; 

     default: 
      return string.Empty; 
    } 
} 

var resultedAndFormatedDictionary = EnumToDictionary<Types>(FormatName); 
+0

'System.Linq.ParallelEnumerable.Cast (System.Linq.ParallelQuery)'이 (가) 주어진 컨텍스트에서 올바르지 않은 '메서드'입니다. ' – Alexandre

+0

타이핑을 수정했습니다. – ChrisWue

+0

좋습니다! 아주 훌륭하고 완벽 해! – Alexandre