开发者

C# Extension Method for generic GetOnlyKeys from IEnumerable<KeyValuePair<int, string>>

I have an IEnumberable> and I want only the list of Keys but cast to the needed type (i.e. perhaps short and not int). This is used in a custom generic multi-select control the binds to but the database needs potientially 'short' to save.

public static IEnumerabl开发者_StackOverflowe<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;
    }

Any advice how to make my generic extension method work?

Thanks!


You want to get only the keys converted to a short?

var myList = valuesDictionary.Select(x => (short)x.Key).ToList();
// A Dictionary can be enumerated like a List<KeyValuePair<TKey, TValue>>

If you want to go to any type, then you would do something like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜