PPC PPC - 1 month ago 15
C# Question

Convert iDictionary<TKey,TValue> into IDictionary<TSomeProperty, ICollection<TValue>>

I have a

IDictionary<TKey, TValue>
referencing my items by a
TKey
hash.

How could I group by those values by, say, the result of
EquivalenceClass TKey.GetEquivalenceClass()
? The result would then fit into a
IDictionary<EquivalenceClass, ICollection<TValue>>


A more concrete example, maybe: given

public enum PlayerPositionGroup {Attacker, Defender}
public class Player{
public PlayerPositionGroup GetPositionGroup(){...}
}


turn

IDictionary<string, Player> SoccerPlayersByName


into

IDictionary<PlayerPositionGroup, ICollection<Player>>

Answer

How about this:

SoccerPlayersByName
.Values
.GroupBy(v => v.GetPositionGroup())
.ToDictionary(g => g.Key, g => g.ToArray());
Comments