2011-01-11 32 views
16

Para propósitos de prueba, tengo que crear un objeto IEnumerable<KeyValuePair<string, string>> con los siguientes pares de valores clave de la muestra:Creando IEnumerable <KeyValuePair <string, string >> ¿Objetos con C#?

Key = Name | Value : John 
Key = City | Value : NY 

¿Cuál es la manera más fácil de hacer esto?

+0

¿Quieres crear 'IEnumerable >'? de que fuente de datos? –

+0

La estructura de datos inicial no es un problema. Puede usar cualquier fuente de datos. El único requisito es tener un IEnumerable con los pares de valores clave anteriores :) –

Respuesta

41

cualquiera de:

values = new Dictionary<string,string> { {"Name", "John"}, {"City", "NY"} }; 

o

values = new [] { 
     new KeyValuePair<string,string>("Name","John"), 
     new KeyValuePair<string,string>("City","NY") 
    }; 

o:

values = (new[] { 
     new {Key = "Name", Value = "John"}, 
     new {Key = "City", Value = "NY"} 
    }).ToDictionary(x => x.Key, x => x.Value); 
4
var List = new List<KeyValuePair<String, String>> { 
    new KeyValuePair<String, String>("Name", "John"), 
    new KeyValuePair<String, String>("City" , "NY") 
}; 
+1

Usar un 'KeyValuePair []' probablemente sería más eficiente que usar 'List >'. – cdhowie

8

Dictionary<string, string> implementa IEnumerable<KeyValuePair<string,string>>.

1
Dictionary<string,string> testDict = new Dictionary<string,string>(2); 
testDict.Add("Name","John"); 
testDict.Add("City","NY"); 

¿Es eso lo que quiere decir, o hay más que eso?

1

Simplemente puede asignar un Dictionary<K, V> a IEnumerable<KeyValuePair<K, V>>

IEnumerable<KeyValuePair<string, string>> kvp = new Dictionary<string, string>(); 

Si eso no funciona, puede intentar -

IDictionary<string, string> dictionary = new Dictionary<string, string>(); 
      IEnumerable<KeyValuePair<string, string>> kvp = dictionary.Select((pair) => pair); 
Cuestiones relacionadas