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;
}
任何意见如何使我的通用扩展方法的工作?
谢谢!
正确的,但我想我要的钥匙的类型转换为通过。 GetKeysOnly –
AdventurGurl
2011-04-07 19:51:07
啊,给我一秒来格式化答案。这很容易。 – Tejs 2011-04-07 19:52:59
该代码给我一个错误:参数2不能从'int'转换为'System.TypeCode' – AdventurGurl 2011-04-07 19:59:18