2011-03-21 36 views
0

我要地圖我Dictionary<int, string>List<Customer>其中Customer有兩個屬性IdName。現在我想將字典的整數Key映射到List<Customer>[i].Key屬性和Value的字典到List<Customer>[i].Name迭代。C# - 字典<key, value>列出<T>

需要幫助。

+1

如何你的字典聲明? – 2011-03-21 16:23:29

回答

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

您還可以使用適當的Customer構造函數(如果可用)而不是示例屬性setter語法。

+0

非常感謝您的快速響應 – 2011-03-21 16:50:51

3

你可以這樣做:

List<Customer> list = theDictionary 
         .Select(e => new Customer { Id = e.Key, Name = e.Value }) 
         .ToList(); 
+0

非常感謝您的快速響應 – 2011-03-21 16:51:47

2
var myList = (from d in myDictionary 
      select new Customer { 
       Key = d.Key, 
       Name = d.Value 
      }).ToList(); 
+0

非常感謝您的快速響應 – 2011-03-21 16:51:16

0

鑑於myDictionary填充和myList IST目標列表:

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