Creating the IEnumerable> Objects with C#?

前端 未结 5 1471
野趣味
野趣味 2020-12-25 11:01

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



        
相关标签:
5条回答
  • 2020-12-25 11:40

    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);
    
    0 讨论(0)
  • 2020-12-25 11:43
    var List = new List<KeyValuePair<String, String>> { 
      new KeyValuePair<String, String>("Name", "John"), 
      new KeyValuePair<String, String>("City" , "NY")
     };
    
    0 讨论(0)
  • 2020-12-25 12:02

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

    0 讨论(0)
  • 2020-12-25 12:04
    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?

    0 讨论(0)
  • 2020-12-25 12:05

    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);
    
    0 讨论(0)
提交回复
热议问题