How to convert a class into Dictionary in C#?
To convert class to Dictionary in C#, we will need to use GetType().GetProperties()
method and then call ToDictionary()
and specify key , value.Remember to include all namespaces:
using System.Linq
, using System.Reflection
, using System.Collections.Generic
.Example
using System;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
public class Location
{
public string city { get; set; }
public string state { get; set; }
public string country { get; set; }
}
public class Example
{
public static void Main()
{
Location loc1 = new Location(); // defining an object
loc1.city = "Detroit"; // populating city attribute
loc1.state = "Michigan"; // populating state attribute
loc1.country = "USA"; // populating country attribute
var myDict = new Dictionary<string, string>();
/* below is how to convert to dictionary */
myDict = loc1.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.ToDictionary(prop => prop.Name, prop => (string)prop.GetValue(loc1, null));
Console.WriteLine(myDict["city"]);
Console.WriteLine(myDict["state"]);
Console.WriteLine(myDict["country"]);
}
}
Output
Detroit
Michigan
USA
Michigan
USA