C#:从 OrderedDictionary.Keys 构建 HashSet 的更优雅的方法?

问题描述

我有一个 OrderedDictionary d 填充字符串键(+ 对象作为值)。我需要将字典键复制到 HashSet<string> hs

我现在是这样做的:

OrderedDictionary d = new OrderedDictionary();
// ... filling d ...

HashSet<string> hs = new HashSet<string>();

foreach (string item in d.Keys)
    hs.Add(item);

我知道字典中有 .CopyTo() 方法来填充字符串数组。有没有更优雅的方法将密钥也复制到 HashSet

更新:建议的 new HashSet<string>(d.Keys.Cast<string>()); 似乎不适用于 OrderedDictionary。编译器(VS2019 Community Ed.)说...

错误 CS1929 'ICollection' 不包含 'Cast' 的定义和最佳扩展方法重载 'EnumerableRowCollectionExtensions.Cast(EnumerableRowCollection)' 需要一个类型为 'EnumerableRowCollection' 的接收器

at tooltip

更新 2:上述更新在添加 using System.Linq; 时有效。

解决方法

当然 - 使用构造函数,相应地转换 Keys 属性序列:

var hs = new HashSet<string>(d.Keys.Cast<string>());

(与 LINQ 一样,请确保为 using 命名空间设置了 System.Linq 指令。)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...