2011-04-07 87 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

相关问题