Domanda

Voglio mappare il mio Dictionary<int, string> a a List<Customer> dove Customer ha due proprietà Id e Name. Ora voglio mappare il mio numero intero Key del dizionario al List<Customer>[i].Key proprietà e Value del dizionario a List<Customer>[i].Name iterativamente.

Hai bisogno di aiuto per lo stesso.

È stato utile?

Soluzione

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();

Puoi anche usare un appropriato Customer costruttore (se disponibile) anziché la sintassi del setter della proprietà di esempio.

Altri suggerimenti

Potresti fare qualcosa come:

 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();

Dato myDictionary è popolato e myList è l'elenco target:

myDictionary.ToList()
            .ForEach(x => 
                     myList.Add( new Customer() {Id = x.Key, Name = x.Value} )
                    );
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top