我要地圖我Dictionary<int, string>
到List<Customer>
其中Customer
有兩個屬性Id
和Name
。現在我想將字典的整數Key
映射到List<Customer>[i].Key
屬性和Value
的字典到List<Customer>[i].Name
迭代。C# - 字典<key, value>列出<T>
需要幫助。
我要地圖我Dictionary<int, string>
到List<Customer>
其中Customer
有兩個屬性Id
和Name
。現在我想將字典的整數Key
映射到List<Customer>[i].Key
屬性和Value
的字典到List<Customer>[i].Name
迭代。C# - 字典<key, value>列出<T>
需要幫助。
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語法。
非常感謝您的快速響應 – 2011-03-21 16:50:51
你可以這樣做:
List<Customer> list = theDictionary
.Select(e => new Customer { Id = e.Key, Name = e.Value })
.ToList();
非常感謝您的快速響應 – 2011-03-21 16:51:47
var myList = (from d in myDictionary
select new Customer {
Key = d.Key,
Name = d.Value
}).ToList();
非常感謝您的快速響應 – 2011-03-21 16:51:16
鑑於myDictionary
填充和myList
IST目標列表:
myDictionary.ToList()
.ForEach(x =>
myList.Add(new Customer() {Id = x.Key, Name = x.Value})
);
如何你的字典聲明? – 2011-03-21 16:23:29