【发布时间】:2020-01-29 16:03:37
【问题描述】:
我这里的问题是将Java的HashMap foreach循环转换成C#的foreach...
public static Map<Genre, List<Band>> PLAYER_ATTRIBUTE_HASHMAP = load();
上面我有 HashMap 的 Java 声明 - 我已经在 C# 中将它转换成这个:
public static Dictionary<Player, List<Attribute>> PLAYER_ATTRIBUTE_DICTIONARY = load();
目前它没有做任何异常,但我遇到了另一个问题,就是 lambda foreach 循环...
在 Java 中它看起来像:
PLAYER_ATTRIBUTE_HASHMAP.forEach((p, a) -> attributes.addAll(a));
它在 C# 中应该是什么样子?
它可以是字典上的正常foreach循环,但我无法理解这个东西..
我有另一个循环,我主要转换它,但与类中的 C# 方法同样存在类似问题。
attributes.AddRange(PLAYER_ATTRIBUTE_DICTIONARY.Values.SelectMany(e => e));
//PLAYER_ATTRIBUTE_DICTIONARY.forEach((p, a)->attributes.AddAll(a));
List<Attribute> distinctAttributes = Attribute.distinctAttributesList(attributes);
List<Player> players = new List<Player>(PLAYER_ATTRIBUTE_DICTIONARY.keySet()); // <--- problem with keyset
PLAYER_ATTRIBUTE_DICTIONARY.forEach((p, a)-> { // <--- and there is also..
List<Double> encodedPlayers = new List<Double>();
List<Double> encodedAttributes = new List<Double>();
foreach (Player player in players)
{
if (player.GetName().Equals(p.GetName()))
{
encodedPlayers.Add(1.0);
}
else
{
encodedPlayers.Add(0.0);
}
}
foreach (Attribute distinctAttribute in distinctAttributes)
{
if (a.stream().anyMatch(attribute->distinctBand.getName().equals(attribute.getName()))) // <--- there is underline with stream and anyMatch
{
encodedAttributes.Add(1.0);
}
else
{
encodedAttributes.Add(0.0);
}
}
dictionary.Add(encodedPlayers, encodedAttributes);
});
return dictionary;
}
【问题讨论】:
-
请不要使用最初从未提及的代码更新“初始”帖子的上下文......
-
@OusmaneD。无论哪种方式,它都是相同的方法,并且包含提到的标题问题,即 foreach with lambda..
-
@roxc:这并不完全正确。如何在字典上执行
foreach的基本问题非常简单。在您更新的代码中,您指出了stream()和anyMatch()等方法调用的错误,这些错误与您最初提出的问题无关。
标签: java c# loops lambda foreach