2011-01-11 91 views
16

出於測試目的,我需要具有下列樣品鍵值對創建IEnumerable<KeyValuePair<string, string>>對象:使用C#創建IEnumerable <KeyValuePair <string,string >>對象?

Key = Name | Value : John 
Key = City | Value : NY 

什麼是最簡單的方法呢?

+0

你想創建`的IEnumerable >`?從哪個數據源? – 2011-01-11 06:26:28

+0

初始數據結構不是問題。您可以使用任何數據源。唯一的要求是有一個具有以上鍵值對的IEnumerable :) – 2011-01-11 06:28:49

回答

41

的任何:

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); 
4
var List = new List<KeyValuePair<String, String>> { 
    new KeyValuePair<String, String>("Name", "John"), 
    new KeyValuePair<String, String>("City" , "NY") 
}; 
8

Dictionary<string, string>實現IEnumerable<KeyValuePair<string,string>>

1
Dictionary<string,string> testDict = new Dictionary<string,string>(2); 
testDict.Add("Name","John"); 
testDict.Add("City","NY"); 

這是你的意思,還是有更多的呢?

1

你可以簡單地分配給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); 
相關問題