2011-01-11 6 views
16

、私は次のサンプルのキーと値のペアでIEnumerable<KeyValuePair<string, string>>オブジェクトを作成する必要があります。C#でIEnumerable <KeyValuePair <文字列、文字列>>オブジェクトを作成しますか?テスト目的のために

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") 
    }; 

または:の

+0

を、あなたは 'のIEnumerable >'を作成しますか?どのデータソースからですか? –

+0

初期のデータ構造は問題ではありません。任意のデータソースを使用できます。唯一の要件は、上記のキー値のペアでIEnumerableを持つことです。 –

答えて

41

任意

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") 
}; 
+1

'KeyValuePair []'を使うと、 'List >'を使うよりも効率的です。 – cdhowie

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); 
関連する問題