2011-04-07 7 views
1

나는 IEnumberable>을 가지고 있으며 키 목록 만 원하지만 필요한 형식 (즉, 짧고 int가 아님)으로 캐스트합니다. 이 바인딩은 사용자 정의 제네릭 다중 선택 제어에 사용되지만 데이터베이스는 잠재적으로 '짧게'저장해야합니다.IEnumerable <KeyValuePair>에서 일반 GetOnlyKeys에 대한 확장 메서드 <int, string>>

public static IEnumerable<T> GetKeysOnly<T>(this IEnumerable<KeyValuePair<int, string>> values) 
    { 
     Dictionary<int, string> valuesDictionary = values.ToDictionary(i => i.Key, i => i.Value); 

     List<int> keyList = new List<int>(valuesDictionary.Keys); 

     // Returns 0 records cuz nothing matches 
     //List<T> results = keyList.OfType<T>().ToList(); 

     // Throws exception cuz unable to cast any items 
     //List<T> results = keyList.Cast<T>().ToList(); 

     // Doesn't compile - can't convert int to T here: (T)i 
     //List<T> results = keyList.ConvertAll<T>(delegate(int i) { return (T)i; }); 

     throw new NotImplementedException(); 
    } 

    public static IEnumerable<short> GetKeysOnly(this IEnumerable<KeyValuePair<int, string>> values) 
    { 
     Dictionary<int, string> valuesDictionary = values.ToDictionary(i => i.Key, i => i.Value); 
     List<int> keyList = new List<int>(valuesDictionary.Keys); 

     // Works but not flexable and requires extension method for each type 
     List<short> results = keyList.ConvertAll(i => (short)i); 
     return results; 
    } 

내 일반적인 확장 방법을 사용하는 방법에 대한 조언이 있으십니까?
감사합니다.

답변

5

키를 단락으로 변환하고 싶습니까? 당신이 어떤 유형으로 이동하려면

var myList = valuesDictionary.Select(x => (short)x.Key).ToList(); 
// A Dictionary can be enumerated like a List<KeyValuePair<TKey, TValue>> 

는, 당신은 다음과 같이 할 것 :

public static IEnumerable<T> ConvertKeysTo<T>(this IEnumerable<KeyValuePair<int, string>> source) 
{ 
    return source.Select(x => (T)Convert.ChangeType(x.Key, typeof(T))); 
    // Will throw an exception if x.Key cannot be converted to typeof(T)! 
} 
+0

수정을,하지만 난 내가 키를 변환 할 유형을 전달하고 싶다. GetKeysOnly AdventurGurl

+0

아, 대답을 포맷하려면 1 초만주세요. 꽤 쉽습니다. – Tejs

+0

그 코드는 저에게 오류를줍니다 : 인수 2는 'int'에서 'System.TypeCode'로 변환 할 수 없습니다. – AdventurGurl

관련 문제