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

c#

我有一个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()字典的方法来填充字符串数组。有没有更优雅的方法将密钥也复制到 a HashSet

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

错误 CS1929“ICollection”不包含“Cast”的定义,并且最佳扩展方法重载“EnumerableRowCollectionExtensions.Cast(EnumerableRowCollection)”需要“EnumerableRowCollection”类型的接收器

更新 2:上述更新在using System.Linq;添加时起作用。

回答

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

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

(与 LINQ 一样,请确保您有命名空间的using指令System.Linq。)


以上是C#:从OrderedDictionary.Keys构建HashSet的更优雅的方法?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>