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


1
Expert's answer
2021-11-15T00:19:55-0500

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
      lst.Add(dic["OneInt"].ToString());
      lst.Add(dic["OneStr"].ToString());
      lst.Add(dic["OnePerson"].ToString());

      //Iterate over each item in list and write to console
      foreach (var item in lst)
      {
        Console.WriteLine(item);
      }
    }
  }

  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!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS