Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用现有哈希集作为键来创建新字典_C#_.net_Dictionary_Hashset - Fatal编程技术网

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

C# 使用现有哈希集作为键来创建新字典,c#,.net,dictionary,hashset,C#,.net,Dictionary,Hashset,如果我有一个T类型的现有哈希集,我将如何从中创建一个字典,如 Dictionary<T, object> tmp = new Dictionary<T, object>(); Dictionary tmp=newdictionary(); 这可以使用以下代码完成 Hashset<string> hashset = new Hashset<string>() foreach(var key in hashset) tmp[key] =

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

Dictionary<T, object> tmp = new Dictionary<T, object>();
Dictionary tmp=newdictionary();
这可以使用以下代码完成

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

foreach(var key in hashset)
    tmp[key] = null;
Hashset Hashset=newhashset()
foreach(hashset中的var键)
tmp[key]=null;
有没有比使用循环更简单的方法呢?

是的,使用同时具有键选择器和值选择器参数的扩展方法

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

因为您正在为值选择
null
,所以必须确保它是null
对象(
null
需要使用类型指定),因此强制转换。

null没有类型。更恰当的说法是:“应该用类型指定null”+1.