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