【问题标题】:C#: more elegant way to build a HashSet from the OrderedDictionary.Keys?C#:从 OrderedDictionary.Keys 构建 HashSet 的更优雅的方式?
【发布时间】: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&lt;string&gt;(d.Keys.Cast&lt;string&gt;()); 似乎不适用于OrderedDictionary。编译器(VS2019 Community Ed.)说...

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

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

【问题讨论】:

标签: c# hashset ordereddictionary


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢,乔恩,但似乎 OrderedDictionary.Keys 不像 Dictionary&lt;,&gt;.Keys 那样支持 .Cast
  • @pepr 根据docs 应该没问题
  • @pepr:“不支持”是什么意思?我不明白为什么它不会...例如gist.github.com/jskeet/bd70e6a01823b5cdd3e4e2b2ed0bcca3 构建。
  • @JonSkeet:我已将更新添加到问题的解释中。
  • @JonSkeet:啊,是的。必须使用 Linq。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-01
  • 2015-03-22
  • 1970-01-01
相关资源
最近更新 更多