If i have an existing Hashset of type T, how would i create a dictionary out of it like;
Dictionary<T, object> tmp = new Dictionary<T, object>();
This can be done using the following code
Hashset<string> hashset = new Hashset<string>()
foreach(var key in hashset)
tmp[key] = null;
Is there an easier way of doing this, rather than having a loop?
Yes, by using the overload of the Enumerable.ToDictionary
extension method that has both a key selector and a value selector parameter.
var dictionary = hashset.ToDictionary(h => h , h => (object)null);
because you're selecting null
for the value, it's necessary to ensure it's a null object
(null
needs to be specified with a type), hence the cast.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With