如果我有一个现有的 T 类型的哈希集,我将如何从中创建一个字典;
Dictionary<T, object> tmp = new Dictionary<T, object>();
这可以使用下面的代码来完成
Hashset<string> hashset = new Hashset<string>()
foreach(var key in hashset)
tmp[key] = null;
有没有比循环更简单的方法?
最佳答案
是的,通过使用 overload of the Enumerable.ToDictionary
具有键选择器和值选择器参数的扩展方法。
var dictionary = hashset.ToDictionary(h => h , h => (object)null);
因为您要为值选择 null
,所以有必要确保它是一个 null object
(null
需要用类型),因此是类型转换。
关于c# - 使用现有的哈希集作为键来创建新字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24060689/