c# - 使用现有的哈希集作为键来创建新字典

标签 c# .net dictionary hashset

如果我有一个现有的 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/

相关文章:

.net - GroupBy 中的内存节省

dictionary - 如何在Kotlin中过滤可变 map

python - "Adding"Python 中的字典?

c# - 如何获取 System.Threading.Timer 周期

c# - 图像调整大小 asp.net mvc 应用程序

c# - .Net Core 2.0 Windows 服务

c# - 为什么一个代码片段可以编译,而另一个不能?

c# - 如何将 confluent-kafka 与 key 存储文件一起使用

c# - EntityType 'Movie_Category_Map' 没有定义键。定义此 EntityType 的键

python - 来自嵌套字典的 Pandas 数据框