Answer to Question #266142 in C# for ivy

Question #266142

How to add value in Dictionary to List

For example:

Dictionary<string, object> = dic <string,object>();

List<string> = list<string>();

Expert's answer

In order to add dictionary value to list we just need to call the Add method on the list and access the key we specified in the dictionary.

We need to take care to call the ToString method when accessing the values in the dictionary because the list will be of type string while the dictionary item value is of type object which is not limited to just strings. Observe the following sample code:

using System;
using System.Collections.Generic;

namespace Q266142

//  How to add value in Dictionary to List

//For example:

//Dictionary<string, object> = dic<string, object>();

//List<string> = list<string>();
  class Program
    static void Main(string[] args)
      // New dictionary of type <string,object>
      Dictionary<string, object> dic = new Dictionary<string, object>();
      //Add <string, int>
      dic["OneInt"] = 1;
      //Add <string, string>
      dic["OneStr"] = "1";
      //Add <string, object>
      dic["OnePerson"] = new Person { Name = "Bob" };

      //New List of strings
      List<string> lst = new List<string>();

      // Add each item from dictionary to list (have to convert each item to string

      //Iterate over each item in list and write to console
      foreach (var item in lst)

  class Person
    public string Name { get; set; }

    // Overriding object ToString method so we get a custom message
    public override string ToString()
      return $"Person with the name: {Name}";

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!


No comments. Be the first!

Leave a comment

New on Blog