How to convert class into Dictionary<string,string>?

Related searches

Now again I am explaining one of my eagerness about Dictionary ! This question is popuped in my mind from answer of my previous question !!

Now the actual point is Can I convert Class into Dictionary ?

In Dictionary I want my class properties as KEY and value of particular property as VALUE

Suppose my class is

public class Location
    public string city { get; set; }
    public string state { get; set; }
    public string country { get; set;

Now suppose my data is

city = Delhi
state = Delhi
country = India

Now you can understand my point easily !

I want to make Dictionary ! That dictionary should be like

Dictionary<string,string> dix = new Dictionary<string,string> ();
dix.add("property_name", "property_value");

I can get the value ! But how can i get property names (not value)?

What should I code to create it dynamic ! That should work for every class which I want ?

You can understand this question as

How can i get list of properties from particular class ?

This is the recipe: 1 reflection, 1 LINQ-to-Objects!

     .GetProperties(BindingFlags.Instance | BindingFlags.Public)
          .ToDictionary(prop => prop.Name, prop => prop.GetValue(someObject, null))

Since I published this answer I've checked that many people found it useful. I invite everyone looking for this simple solution to check another Q&A where I generalized it into an extension method: Mapping object to dictionary and vice versa.

How to convert object to Dictionary<TKey, TValue> in C#?, public static class ObjectToDictionaryHelper. {. public static IDictionary<string, object> ToDictionary(this object source). {. return source.ToDictionary<object>();. }. Convert dictionary keys to camel case; Convert enums to strings and camel case; For other scenarios that require special handling of JSON property names and values, you can implement custom converters. Customize individual property names. To set the name of individual properties, use the [JsonPropertyName] attribute.

Here a example with reflection without linq:

    Location local = new Location(); = "Lisbon"; = "Portugal";
    local.state = "None";

    PropertyInfo[] infos = local.GetType().GetProperties();

    Dictionary<string,string> dix = new Dictionary<string,string> ();

    foreach (PropertyInfo info in infos)
        dix.Add(info.Name, info.GetValue(local, null).ToString());

    foreach (string key in dix.Keys)
        Console.WriteLine("nameProperty: {0}; value: {1}", key, dix[key]);


C# convert an object to a dictionary of its properties � GitHub, Code to convert plain old C# objects to dictionaries usinf Linq Expressions. This approach is [TestClass]. public class ObjectToDictionaryTest. Python object and dictionary convertion Jun 14, 2012 #python #programming. When programing in Python, sometimes you want to convert an object to dictionary and vise versal. In this article, I share my expericences to do that. Convert from class to dictionary

I would like to add an alternative to reflection, using JToken. You will need to check the benchmark difference between the two to see which has better performance.

var location = new Location() { City = "London" };
var locationToken = JToken.FromObject(location);
var locationObject = locationObject.Value<JObject>();
var locationPropertyList = locationObject.Properties()
    .Select(x => new KeyValuePair<string, string>(x.Name, x.Value.ToString()));

Note this method is best for a flat class structure.

Fast Conversion of Objects to Dictionaries in C#, Following conversions from list to dictionary will be covered here, Convert a List to Dictionary with same values; Convert List items as keys in dictionary with enumerated value; Convert two lists to dictionary; Convert a list of tuples to dictionary; Convert a List to Dictionary with same values. Suppose we have a list of strings i.e.

Give this a try.

    public static Dictionary<string, object> ObjectToDictionary(object obj)
        Dictionary<string, object> ret = new Dictionary<string, object>();

        foreach (PropertyInfo prop in obj.GetType().GetProperties())
            string propName = prop.Name;
            var val = obj.GetType().GetProperty(propName).GetValue(obj, null);
            if (val != null)
                ret.Add(propName, val.ToString());
                ret.Add(propName, null);

        return ret;

Python | Convert dictionary object into string Last Updated: 17-10-2019 Dictionary is an important container and used almost in every code of day-day programming as well as web-development, more it is used, more is the requirement to master it and hence knowledge of its operations is necessary.

protected string getExamTimeBlock(object dataItem)
    var dt = ((System.Collections.Specialized.StringDictionary)(dataItem));

    if (SPContext.Current.Web.CurrencyLocaleID == 1033) return dt["en"];
    else return dt["sv"];

In this tutorial, we will learn how to convert a dictionary into a list in Python with three different methods. A Dictionary is an unordered sequence that is mutable. Certainly, it is used for more flexible operations.

I have a bytes type object like this: b"{'one': 1, 'two': 2}" I need to get the dictionary from that using python code. I am converting it into string and then converting into dictionary as foll

How to convert class into Dictionary<string,string>? 14. Cast dynamic object to type using reflection c#. 8. Persisting dynamic object in DynamoDB with .NET SDK. 3.

Given a list, write a Python program to convert the given list to dictionary such that all the odd elements have the key, and even number elements have the value. Since python dictionary is unordered, the output can be in any order.

  • Can you try to reword the question please? I have no real idea what you are trying to achieve.
  • Insort ! I want all variables' name of particular class ! Is this possible ?
  • @NoOne I've answered you, but you need to learn something more about OOP. You're talking about properties. And class-level "variables" are called fields. It's important to call everything by its name as understanding you'd easier than now! ;)
  • @MatíasFidemraizer Sorry ! My mistake I should use "property" I have edited !
  • @Chintan I dont know where you plan on using a dictionary of a class, note, that in contrary to your class where "Country" can be a property of type Country and city is of type string, in a dictionary you have to specify the most basic type you are going to store (most likely object) which will make your life harder further along the road.
  • what if I see "intrinsic" properties like "GenericEqualityComparer", rather than properties I explicitly declared? I've tried BindingFlags.DeclaredOnly.
  • UPDATE nevermind - I found that the method using this reflection (itself in an object extension) ended up calling itself with the converted result, so my extension was getting called on an object AND THEN on the resulting dictionary.
  • I can't compile this in Unity3D, am I missing an assembly reference?
  • For other Unity3D users - add usings to top and remember the code returns System.Oject not unity objects. using System.Collections.Generic; using System.Linq; using System.Reflection;
  • This saved me at least a days worth of work. Thanks so much I would vote you up twice if I could!
  • var locationObject = locationObject.Value<JObject>();?
  • Here's a more compact version: var props = JToken.FromObject(query) .Value<JObject>() .Properties() .ToDictionary(k => k.Name, v => $"{v.Value}");
  • It works but I'd argue if this is an extension method abstracting the logic the syntax of this is over compressed and obscured by the language "sugar". In a scenario like this I'd leave the logic in it's more verbose format as it makes it much easier to read.