views:

136

answers:

4

Suppose I have a Dictionary like so:

Dictionary<string, Stream>

How can I get a list (or IEnumerable or whatever) of JUST the Keys from this dictionary? Is this possible?

I could enumerate the dictionary, and extract the keys one by one, but I was hoping to avoid this.

In my instance, the Dictionary contains a list of filenames (file1.doc, filex.bmp etc...) and the stream content of the file from another part of the application.

+3  A: 

KeyCollection Dictionary(TKey, TValue).Keys

Juliet
I initially tried this however it didn't provider me with what i want - is this acceptable? var x = (IEnumerable<string>)attachments.Keys; - casting it as a IEnumerable of string??
alex
KeyCollection already implements IEnumerable<string>: http://msdn.microsoft.com/en-us/library/3fcwy8h6.aspx , no casting needing.
Juliet
@alex `KeyCollection` is already an `IEnumerable<string>` - there's no need for the cast.
Frank Krueger
+1  A: 

Dictionary(TKey, TValue).Keys

Typically you can discover these things through code-completion/IntelliSense.

Similarly, there is a Values property:

Ryan Emerle
+1  A: 

Dictionary<T,T>.Keys returns a KeyCollection. This has the IEnumerable interface.

so...

foreach(string key in Dictionary<string,Stream>.Keys)
{


}
Kevin
A: 
public IEnumerable<long> ReturnSomeKeys()
{
    var foo = new Dictionary<long, string>();
    return foo.Keys;
}

This does what you want.

Jaxidian