pepr
pepr

Reputation: 20770

C#: more elegant way to build a HashSet from the OrderedDictionary.Keys?

I have an OrderedDictionary d filled with string keys (+ objects as the value). I need to copy the dictionary keys to a HashSet<string> hs.

I am doing it now like this:

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

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

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

I know there is .CopyTo() method of the dictionary to fill the array of strings. Is there any more elegant way to copy the keys also to a HashSet?

Update: It seems that the suggested new HashSet<string>(d.Keys.Cast<string>()); does not work for the OrderedDictionary. The compiler (VS2019 Community Ed.) says...

Error CS1929 'ICollection' does not contain a definition for 'Cast' and the best extension method overload 'EnumerableRowCollectionExtensions.Cast(EnumerableRowCollection)' requires a receiver of type 'EnumerableRowCollection'

at tooltip

Update 2: The above Update works when using System.Linq; is added.

Upvotes: 0

Views: 247

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500855

Sure - use the constructor, casting the Keys property sequence accordingly:

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

(As ever with LINQ, make sure you have a using directive for the System.Linq namespace.)

Upvotes: 7

Related Questions