出於測試目的,我需要具有下列樣品鍵值對創建IEnumerable<KeyValuePair<string, string>>
對象:使用C#創建IEnumerable <KeyValuePair <string,string >>對象?
Key = Name | Value : John
Key = City | Value : NY
什麼是最簡單的方法呢?
出於測試目的,我需要具有下列樣品鍵值對創建IEnumerable<KeyValuePair<string, string>>
對象:使用C#創建IEnumerable <KeyValuePair <string,string >>對象?
Key = Name | Value : John
Key = City | Value : NY
什麼是最簡單的方法呢?
的任何:
values = new Dictionary<string,string> { {"Name", "John"}, {"City", "NY"} };
或
values = new [] {
new KeyValuePair<string,string>("Name","John"),
new KeyValuePair<string,string>("City","NY")
};
或:
values = (new[] {
new {Key = "Name", Value = "John"},
new {Key = "City", Value = "NY"}
}).ToDictionary(x => x.Key, x => x.Value);
var List = new List<KeyValuePair<String, String>> {
new KeyValuePair<String, String>("Name", "John"),
new KeyValuePair<String, String>("City" , "NY")
};
Dictionary<string, string>
實現IEnumerable<KeyValuePair<string,string>>
。
Dictionary<string,string> testDict = new Dictionary<string,string>(2);
testDict.Add("Name","John");
testDict.Add("City","NY");
這是你的意思,還是有更多的呢?
你可以簡單地分配給Dictionary<K, V>
IEnumerable<KeyValuePair<K, V>>
IEnumerable<KeyValuePair<string, string>> kvp = new Dictionary<string, string>();
如果不工作,你可以嘗試 -
IDictionary<string, string> dictionary = new Dictionary<string, string>();
IEnumerable<KeyValuePair<string, string>> kvp = dictionary.Select((pair) => pair);
你想創建`的IEnumerable>`?從哪個數據源? –
2011-01-11 06:26:28
初始數據結構不是問題。您可以使用任何數據源。唯一的要求是有一個具有以上鍵值對的IEnumerable :) – 2011-01-11 06:28:49