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

Huzefa Kagdi picture Huzefa Kagdi · Mar 21, 2011 · Viewed 12.6k times · Source

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.

Answer

Jon picture Jon · Mar 21, 2011
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.