F# iteration over a Dictionary
I'm just starting with F# and I want to iterate over a dictionary, getting the keys and values.
So in C#, I'd put:
IDictionary resultSet = test.GetResults;
foreach (DictionaryEntry de in resultSet)
{
Console.WriteLine("Key = {0}, Valu开发者_开发技巧e = {1}", de.Key, de.Value);
}
I can't seem to find a way to do this in F# (not one that compiles anyway).
Could anybody please suggest the equivalent code in F#?
Cheers,
Crush
What is the type of your dictionary?
If it is non-generic IDictionary
as your code snippet suggests, then try the following (In F#, for
doesn't implicitly insert conversions, so you need to add Seq.cast<>
to get a typed collection that you can easily work with):
for entry in dict |> Seq.cast<DictionaryEntry> do
// use 'entry.Value' and 'entry.Key' here
If you are using generic IDictionary<'K, 'V>
then you don't need the call to Seq.cast
(if you have any control over the library, this is better than the previous option):
for entry in dict do
// use 'entry.Value' and 'entry.Key' here
If you're using immutable F# Map<'K, 'V>
type (which is the best type to use if you're writing functional code in F#) then you can use the solution by Pavel or you can use for
loop together with the KeyValue
active pattern like this:
for KeyValue(k, v) in dict do
// 'k' is the key, 'v' is the value
In both of the cases, you can use either for
or various iter
functions. If you need to perform something with side-effects then I would prefer for
loop (and this is not the first answer where I am mentioning this :-)), because this is a language construct designed for this purpose. For functional processing you can use various functions like Seq.filter
etc..
resultSet |> Map.iter (fun key value ->
printf "Key = %A, Value = %A\n" key value)
(This is a shorter answer than Tomas' one, going to the point.) Dictionaries are mutable, in F# it's more natural to use Maps (immutable). So if you're dealing with map: Map<K,V>
, iterate through it this way:
for KeyValue(key,value) in map do
DoStuff key value
精彩评论