F# iteration over a Dictionary

北战南征 提交于 2019-12-12 08:35:08

问题


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}, Value = {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


回答1:


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..




回答2:


resultSet |> Map.iter (fun key value ->
   printf "Key = %A, Value = %A\n" key value)



回答3:


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


来源:https://stackoverflow.com/questions/3267590/f-iteration-over-a-dictionary

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!