Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast a hashtable.Keys into List<int> or other IEnumerable<int>

Tags:

c#

hashtable

key

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 ask me what problem I'm trying to solve, or anything like that. This is a pure and simple CS question.

I want to know if anyone knows of a way to take the keys from a Hashtable and cast them into a List<int> or some other type of IEnumerable<int> (given of course that my keys are in fact integers).

Given that I can do this with no problem:

foreach (int key in hashtable.Keys)

Why does this give me errors?

(List<int>)hashtable.Keys
like image 836
Samo Avatar asked Mar 08 '11 17:03

Samo


2 Answers

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

like image 71
Quintin Robinson Avatar answered Oct 25 '22 13:10

Quintin Robinson


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.

like image 30
KeithS Avatar answered Oct 25 '22 13:10

KeithS