来自IEnumerable的通用GetOnlyKeys的C#扩展方法<keyvaluepair <int,string =“”>&gt; </keyvaluepair <int,>

时间:2011-04-07 19:42:57

标签: c# methods ienumerable

我有一个IEnumberable&gt;我只想要键列表但转换为所需类型(即可能短而不是int)。这用于绑定到的自定义通用多选控件,但数据库需要在资源上“短”才能保存。

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;
    }

有关如何使我的通用扩展方法有效的建议吗? 谢谢!

1 个答案:

答案 0 :(得分: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)!
}