2010-03-12 16 views

risposta

38

In .NET4 è possibile utilizzare il built-in Zip metodo per unire le due sequenze, seguiti da una chiamata ToDictionary:

var keys = new List<int> { 1, 2, 3 }; 
var values = new List<string> { "one", "two", "three" }; 

var dictionary = keys.Zip(values, (k, v) => new { Key = k, Value = v }) 
        .ToDictionary(x => x.Key, x => x.Value); 
20
 List<string> keys = new List<string>(); 
     List<string> values = new List<string>(); 
     Dictionary<string, string> dict = keys.ToDictionary(x => x, x => values[keys.IndexOf(x)]); 

Questo naturalmente presuppone che la lunghezza di ciascuna lista sia la stessa e che i tasti siano unici.

UPDATE:This answer è molto più efficiente e deve essere utilizzato per elenchi di dimensioni non banali.

+0

Preferisco utilizzare un ciclo, invece di utilizzare questo. Ancora +1 per la risposta. – Steven

+0

Era così. Grazie!!! – VNarasimhaM

+0

perché dovresti usare loops al posto di LINQ? Ho pensato che questo codice sia molto più succinto e leggibile rispetto al ciclo for. – VNarasimhaM

4

È possibile includere l'indice in un'espressione Select per rendere questo efficace:

 var a = new List<string>() { "A", "B", "C" }; 
     var b = new List<string>() { "1", "2", "3" }; 

     var c = a.Select((x, i) => new {key = x, value = b[i]}).ToDictionary(e => e.key, e => e.value); 

     foreach (var d in c) 
      Console.WriteLine(d.Key + " = " + d.Value); 

     Console.ReadKey(); 
-3

È possibile utilizzare questo codice e funziona perfettamente.

C# Codice:

var keys = new List<string> { "Kalu", "Kishan", "Gourav" }; 
     var values = new List<string> { "Singh", "Paneri", "Jain" }; 

     Dictionary<string, string> dictionary = new Dictionary<string, string>(); 
     for (int i = 0; i < keys.Count; i++) 
     { 

      dictionary.Add(keys[i].ToString(), values[i].ToString()); 
     } 
     foreach (var data in dictionary) 
     { 
      Console.WriteLine("{0} {1}", data.Key, data.Value); 

     } 
     Console.ReadLine(); 

Output su schermo:

enter image description here

+0

Un'attività troppo ingombrante – netfed

1
var dic = keys.Zip(values, (k, v) => new { k, v }) 
      .ToDictionary(x => x.k, x => x.v); 
+2

Questo aggiunge davvero qualcosa alla [LukeH] (http://stackoverflow.com/users/55847/lukeh)? [Risposta di 5 anni] (http://stackoverflow.com/a/ 2434647/215380)? – Rawling

Problemi correlati