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!

 someObject.GetType()
     .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();
    local.city = "Lisbon";
    local.country = "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]);
    }

    Console.Read();

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());
            }
            else
            {
                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.