简体   繁体   中英

C# - Dictionary<key, value> to List<T>

I want to map my Dictionary<int, string> to a List<Customer> where Customer has two properties Id and Name . Now I want to map my integer Key of the dictionary to the List<Customer>[i].Key property and Value of the dictionary to List<Customer>[i].Name iteratively.

Need help for the same.

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

You can also use an appropriate Customer constructor (if available) instead of the example property setter syntax.

You could do something like:

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

Given myDictionary is populated and myList ist the target list:

myDictionary.ToList()
            .ForEach(x => 
                     myList.Add( new Customer() {Id = x.Key, Name = x.Value} )
                    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM