How to add value in Dictionary to List
For example:
Dictionary<string, object> = dic <string,object>();
List<string> = list<string>();
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}";
}
}
}
Comments
Leave a comment