创建 IEnumerable>> C# 的对象?

发布于 2024-10-11 19:46:39 字数 213 浏览 2 评论 0 原文

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

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

最简单的方法是什么?

For testing purposes, I need to create an IEnumerable<KeyValuePair<string, string>> object with the following sample key value pairs:

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

What is the easiest approach to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

ˉ厌 2024-10-18 19:46:39

任何:

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

any of:

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

or

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

or:

values = (new[] {
      new {Key = "Name", Value = "John"},
      new {Key = "City", Value = "NY"}
   }).ToDictionary(x => x.Key, x => x.Value);
合久必婚 2024-10-18 19:46:39

Dictionary 实现 IEnumerable>

Dictionary<string, string> implements IEnumerable<KeyValuePair<string,string>>.

请远离我 2024-10-18 19:46:39
var List = new List<KeyValuePair<String, String>> { 
  new KeyValuePair<String, String>("Name", "John"), 
  new KeyValuePair<String, String>("City" , "NY")
 };
var List = new List<KeyValuePair<String, String>> { 
  new KeyValuePair<String, String>("Name", "John"), 
  new KeyValuePair<String, String>("City" , "NY")
 };
月竹挽风 2024-10-18 19:46:39
Dictionary<string,string> testDict = new Dictionary<string,string>(2);
testDict.Add("Name","John");
testDict.Add("City","NY");

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

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

Is that what you mean, or is there more to it?

冷了相思 2024-10-18 19:46:39

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

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

You can simply assign a Dictionary<K, V> to IEnumerable<KeyValuePair<K, V>>

IEnumerable<KeyValuePair<string, string>> kvp = new Dictionary<string, string>();

If that does not work you can try -

IDictionary<string, string> dictionary = new Dictionary<string, string>();
            IEnumerable<KeyValuePair<string, string>> kvp = dictionary.Select((pair) => pair);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文