Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use existing Hashset as Keys to create new dictionary

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?

like image 243
Ramie Avatar asked Jan 11 '23 11:01

Ramie


1 Answers

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.

like image 69
spender Avatar answered Jan 18 '23 08:01

spender