C# - Diccionario para enumerar
-
28-10-2019 - |
Pregunta
Quiero mapear mi Dictionary<int, string>
a un List<Customer>
dónde Customer
tiene dos propiedades Id
y Name
. Ahora quiero mapear mi entero Key
del diccionario al List<Customer>[i].Key
propiedad y Value
del diccionario a List<Customer>[i].Name
iterativamente.
Necesito ayuda para lo mismo.
Solución
var dict = new Dictionary<int, string>(); // populate this with your data
var list = dict.Select(pair => new Customer { Id = pair.Key, Name = pair.Value }).ToList();
También puedes usar un apropiado Customer
Constructor (si está disponible) en lugar de la sintaxis de Setter de propiedad de ejemplo.
Otros consejos
Podrías hacer algo como:
List<Customer> list = theDictionary
.Select(e => new Customer { Id = e.Key, Name = e.Value })
.ToList();
var myList = (from d in myDictionary
select new Customer {
Key = d.Key,
Name = d.Value
}).ToList();
Dado myDictionary
está poblado y myList
ist la lista de objetivos:
myDictionary.ToList()
.ForEach(x =>
myList.Add( new Customer() {Id = x.Key, Name = x.Value} )
);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow