Cast a hashtable.Keys into List or other IEnumerable

后端 未结 6 594
伪装坚强ぢ
伪装坚强ぢ 2020-12-31 16:40

I know, I have other options, e.g. I could maintain a separate list of keys. Please don\'t suggest other options. I simply want to know if I can pull this off. Please don\'t

相关标签:
6条回答
  • 2020-12-31 16:52

    Because foreach requires hashtable.Keys to be an IEnumerable<TKey>, which it is. However, hashtable.Keys is NOT a List<TKey>; it is a simple ICollection, which is not the same. To convert it to a List, try some Linq:

    List<int> keys = hashtable.Keys.OfType<int>().ToList();
    

    This will basically enumerate through the Keys collection and add each element to a new List, then give you the List. OfType() is "safer" than Cast; Cast just tries to treat the whole collection as being an IEnumerable<int>, which can result in runtime errors or unpredictable behavior if any contained element is null or cannot be implicitly cast to an integer. OfType, by contrast, will iterate through the source and produce an enumerable of only the elements that actually are ints. Either works if you are SURE that all keys are integers.

    0 讨论(0)
  • 2020-12-31 16:53

    Because hashtable.Keys is a collection of objects which is not covariant with a list of integers.

    0 讨论(0)
  • 2020-12-31 16:57

    Either use Dictionary instead of non-generic version. Or use CastTo extension method. See http://msdn.microsoft.com/en-us/library/system.collections.icollection.aspx for details on non-generic collection returned by Hastable.Key as well link to casting method you can use.

    0 讨论(0)
  • 2020-12-31 17:00

    If you have LINQ extension methods available you can do the following..

    List<int> keys = hashtable.Keys.Cast<int>().ToList();
    

    Also

    List<int> keys = hashtable.Keys.OfType<int>().ToList();
    

    might work depending on automatic boxing

    0 讨论(0)
  • 2020-12-31 17:00

    You can do ICollection<int> keyCols = hashtable.Keys;

    0 讨论(0)
  • 2020-12-31 17:10

    Your foreach loop will throw an InvalidCastException if the Keys collection doesn't contain an int.

    The cast to List<int> fails because the compiler can't convert a non-generic ICollection to a specific ICollection<T>

    0 讨论(0)
提交回复
热议问题