2011-04-07 129 views
1

我有一個IEnumberable>,我只想要Keys的列表,但是轉換爲所需的類型(即可能是short而不是int)。這用於一個自定義通用多選控件綁定到,但數據庫需要potientially'短'來保存。從IEnumerable獲取泛型GetOnlyKeys的C#擴展方法<KeyValuePair <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 2011-04-07 19:51:07

+0

啊,給我一秒來格式化答案。這很容易。 – Tejs 2011-04-07 19:52:59

+0

該代碼給我一個錯誤:參數2不能從'int'轉換爲'System.TypeCode' – AdventurGurl 2011-04-07 19:59:18

相關問題