1

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.

AakashM
  • 62,551
  • 17
  • 151
  • 186
Huzefa Kagdi
  • 159
  • 1
  • 4
  • 11

4 Answers4

12
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.

Jon
  • 428,835
  • 81
  • 738
  • 806
3

You could do something like:

 List<Customer> list = theDictionary
                         .Select(e => new Customer { Id = e.Key, Name = e.Value })
                         .ToList();
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
2
var myList = (from d in myDictionary
             select new Customer {
               Key = d.Key,
               Name = d.Value
             }).ToList();
John Hartsock
  • 85,422
  • 23
  • 131
  • 146
0

Given myDictionary is populated and myList ist the target list:

myDictionary.ToList()
            .ForEach(x => 
                     myList.Add( new Customer() {Id = x.Key, Name = x.Value} )
                    );
Dennis Traub
  • 50,557
  • 7
  • 93
  • 108