【发布时间】:2021-05-29 04:14:50
【问题描述】:
我有一个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”类型的接收器
更新 2: 上述更新在添加 using System.Linq; 时有效。
【问题讨论】:
-
事先考虑设置容量-docs.microsoft.com/en-us/dotnet/api/…。
标签: c# hashset ordereddictionary