C# to dictionary example
Example 1: access dic by key c#
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add("apple", 1);
dictionary.Add("windows", 5);
if (dictionary.ContainsKey("apple"))
{
int value = dictionary["apple"];
Console.WriteLine(value);
}
if (!dictionary.ContainsKey("acorn"))
{
Console.WriteLine(false);
}
}
}
Example 2: c# dictionaries
IDictionary<int, string> dict = new Dictionary<int, string>();
Dictionary<int, string> dict = new Dictionary<int, string>();
Example 3: convert dictionary to object c#
class ObjectToMapTo
{
public int ID;
public string Name;
public bool IsAdmin;
public override string ToString()
{
return $"(ID={ID} Name={Name} IsAdmin={IsAdmin})";
}
}
static object MapDictToObj(Dictionary<string, object> dict, Type destObject)
{
object returnobj = Activator.CreateInstance(destObject);
foreach (string key in dict.Keys)
{
object value = dict[key];
FieldInfo field = destObject.GetField(key);
if (field != null)
{
field.SetValue(returnobj, value);
}
}
return returnobj;
}
static void Main(string[] args)
{
Dictionary<string, object> dict = new Dictionary<string, object>();
dict["ID"] = 1000;
dict["Name"] = "This is a name";
dict["IsAdmin"] = true;
ObjectToMapTo obj = (ObjectToMapTo)MapDictToObj(dict, typeof(ObjectToMapTo));
Console.WriteLine(obj);
Console.ReadKey();
}
Example 4: c sharp add item to dictionary
dict.Add(1,"One");