【问题标题】:Use existing Hashset as Keys to create new dictionary使用现有的 Hashset 作为键来创建新字典
【发布时间】:2014-07-26 11:25:22
【问题描述】:

如果我有一个 T 类型的现有 Hashset,我将如何从中创建字典;

Dictionary<T, object> tmp = new Dictionary<T, object>();

这可以使用以下代码完成

Hashset<string> hashset = new Hashset<string>()

foreach(var key in hashset)
    tmp[key] = null;

有没有比循环更简单的方法?

【问题讨论】:

    标签: c# .net dictionary hashset


    【解决方案1】:

    是的,通过使用同时具有键选择器和值选择器参数的overload of the Enumerable.ToDictionary 扩展方法。

    var dictionary = hashset.ToDictionary(h => h , h => (object)null);
    

    因为您选择 null 作为值,所以必须确保它是 null objectnull 需要指定类型),因此需要进行强制转换。

    【讨论】:

    • null 没有类型。更恰当的说法是:“null 应该指定一个类型”。 +1
    猜你喜欢
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 2022-06-22
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 2019-12-27
    • 2017-12-17
    相关资源
    最近更新 更多