使用C#创建IEnumerable <KeyValuePair >对象?

出于测试目的,我需要使用以下示例键值对创建IEnumerable<KeyValuePair>对象:

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

这样做最简单的方法是什么?

任何:

 values = new Dictionary { {"Name", "John"}, {"City", "NY"} }; 

要么

 values = new [] { new KeyValuePair("Name","John"), new KeyValuePair("City","NY") }; 

要么:

 values = (new[] { new {Key = "Name", Value = "John"}, new {Key = "City", Value = "NY"} }).ToDictionary(x => x.Key, x => x.Value); 

Dictionary实现IEnumerable>

 var List = new List> { new KeyValuePair("Name", "John"), new KeyValuePair("City" , "NY") }; 
 Dictionary testDict = new Dictionary(2); testDict.Add("Name","John"); testDict.Add("City","NY"); 

这是你的意思,还是还有更多呢?

您可以简单地将Dictionary分配给IEnumerable>

 IEnumerable> kvp = new Dictionary(); 

如果这不起作用,你可以尝试 –

 IDictionary dictionary = new Dictionary(); IEnumerable> kvp = dictionary.Select((pair) => pair);