2010-11-02 5 views
2

Pour pouvoir trier un dictionnaire en valeur J'utilise ce code:Convertir une liste (de KeyValuePair (Of String, Int32) dans un dictionnaire (de String, Int32) en utilisant .ToDictionary

Dim idCurrentJobs As IDictionary(Of String, Int32) = New Dictionary(Of String, Int32) 
'The string in the dictionary represents a jobname and the integer is a counter for how many jobs im currently are running in the application' 
idCurrentJobs.Add("JobName1", 2) 
idCurrentJobs.Add("JobName2", 1) 
idCurrentJobs.Add("JobName3", 2) 
idCurrentJobs.Add("JobName4", 5) 
idCurrentJobs.Add("JobName5", 3) 
idCurrentJobs.Add("JobName6", 4) 

Dim jobsSortedByCount As List(Of KeyValuePair(Of String, Int32)) = New List(Of KeyValuePair(Of String, Int32))(idCurrentJobs) 
jobsSortedByCount.Sort(Function(firstPair As KeyValuePair(Of String, Int32), nextPair As KeyValuePair(Of String, Int32)) firstPair.Value.CompareTo(nextPair.Value)) 

idCurrentJobs = jobsSortedByCount.ToDictionary(Of List(Of KeyValuePair(Of String, Int32)))(Function(pair As KeyValuePair(Of String, Int32)) pair.Key) 

Lorsque j'utilise la méthode .ToDictionary pour convertir l'objet List en un objet Directory, j'obtiens une erreur sur le "paire.Key" en disant:

La valeur du type 'Chaîne' ne peut pas être convertie à 'System.Collections.Generic.List (Of System.Collections.Generic.KeyValuePair (Of String, Integer))

Comment devrais-je utiliser le .ToDictionary pour obtenir un objet Dictionary à partir de ma liste d'objets?

Si je change la ligne avec la méthode .ToDictionary à ceci:

idCurrentJobs = jobsSortedByCount.ToDictionary(Of KeyValuePair(Of String, Int32))(Function(pair As KeyValuePair(Of String, Int32)) pair) 

Je reçois cette erreur en raison de "Strict On":

Option Strict On implicite conversions n'autorise de 'System.Collections.Generic.Dictionary (Of System.Collections.Generic.KeyValuePair (Of Chaîne, Integer), System.Collections.Generic.KeyValuePair (Of String, Integer)) » à 'System.Collections.Generic.IDictionary (de String, Integer)'

Comment puis-je résoudre ce problème?

Répondre

7

Cela fonctionne, même avec Option Strict On.

Dim list As List(Of KeyValuePair(Of String, Int32)) 
Dim dict As IDictionary(Of String, Int32) = 
    list.ToDictionary(Function(p) p.Key, Function(p) p.Value) 

Le problème est ici de votre code:

ToDictionary(Of List(Of KeyValuePair(Of String, Int32))) 
+0

Merci beaucoup! Mais pourquoi tout le monde inclut-il la lettre "p" quand on utilise Function(), cela a-t-il un sens? –

+0

Non, c'est juste un nom; vous pouvez l'appeler comme vous voulez. – jason

+0

Oui, mais pourquoi "p"? :) Que dois-je nommer si je veux être aussi clair que possible? –

2

Essayez:

idCurrentJobs = jobsSortedByCount.ToDictionary(Of String, Int32)(Function(p) p.Key, Function(p) p.Value) 
Questions connexes