在字典上进行F#迭代 [英] F# iteration over a Dictionary

查看:88
本文介绍了在字典上进行F#迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是从F#开始,我想遍历字典,获取键和值.

I'm just starting with F# and I want to iterate over a dictionary, getting the keys and values.

所以在C#中,我输入:

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);
}

我似乎找不到在F#中执行此操作的方法(无论如何也无法编译).

I can't seem to find a way to do this in F# (not one that compiles anyway).

有人可以在F#中建议等效代码吗?

Could anybody please suggest the equivalent code in F#?

干杯

暗恋

推荐答案

您的字典的类型是什么?

What is the type of your dictionary?

如果您的代码段所建议的不是通用的IDictionary,请尝试以下操作(在F#中,for不会隐式地插入转换,因此您需要添加Seq.cast<>以获得类型化的集合,您可以轻松地与之合作):

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

如果您使用的是通用IDictionary<'K, 'V>,则无需调用Seq.cast(如果您对库有任何控制权,那么它会比上一个选项更好):

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

如果您使用的是不可变的F#Map<'K, 'V>类型(如果您正在用F#编写功能代码,这是使用的最佳类型),则可以使用Pavel的解决方案,也可以将for循环与像这样的KeyValue活动模式:

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

在两种情况下,您都可以使用for或各种iter功能.如果您需要执行某些具有副作用的操作,那么我更喜欢for循环(这不是我提到此的第一个答案:-)),因为这是为此目的而设计的语言构造.对于功能处理,您可以使用各种功能,例如Seq.filter等.

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

这篇关于在字典上进行F#迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆