C# IEnumerable

C# IEnumerable,c#,methods,ienumerable,C#,Methods,Ienumerable,我有一个IEnumberable>,我只需要键列表,但强制转换为所需的类型,即可能是short而不是int。这在绑定到的自定义通用多选控件中使用,但数据库可能需要“short”来保存 public static IEnumerable<T> GetKeysOnly<T>(this IEnumerable<KeyValuePair<int, string>> values) { Dictionary<int, strin

我有一个IEnumberable>,我只需要键列表,但强制转换为所需的类型,即可能是short而不是int。这在绑定到的自定义通用多选控件中使用,但数据库可能需要“short”来保存

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;
    }
如何让我的泛型扩展方法工作,有什么建议吗?
谢谢

您只想将密钥转换为短密钥吗

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)!
}

您只想将密钥转换为短密钥吗

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)!
}

正确,但我想传入要将键转换为的类型。GetKeysOnlyAh,给我一秒钟来格式化答案。这很简单。这段代码给了我一个错误:参数2不能从'int'转换为'System.TypeCode'Oops,我把参数倒过来了。太棒了!非常感谢你!!正确,但我想传入要将键转换为的类型。GetKeysOnlyAh,给我一秒钟来格式化答案。这很简单。这段代码给了我一个错误:参数2不能从'int'转换为'System.TypeCode'Oops,我把参数倒过来了。太棒了!非常感谢你!!