Search code examples
c#.netstringstringtokenizer

Get property names of a object as a Dictionary<string,string> in .net


I working on a string tokenizer function.

This is the sample object

    var obj= new
    {
        Order= new
        {
            CustomerName = "John",
            OrderTotal= "10.50",
            Qty =2,
            Address= new
            {
                Street= "Park Road",
                Country= "UAS"
            }
        }
    };

I need to get property vs values onto Dictionary<string, string>

expecting result :

     <Order.CustomerName,"John">
     <Order.OrderTotal,"10.50">
     <Order.Qty ,"2">
     <Order.CustomerName.Address.Street,"Park Road">
     <Order.CustomerName.Address.Country,"USA">

This is how I tried

private Dictionary<string, string> GetValueByPropertyToken(object obj)
{
    var result = new Dictionary<string, string>();
    // get the type:
    var objType = obj.GetType();
    // iterate the properties
    var prop = (from property in objType.GetProperties() select property).ToList();

    foreach (var item in prop)
    {
        var name = item.Name;
        var nextProperty = item?.GetValue(obj);
    }

    return result;
}

Solution

  • firslty, you did not add dictionary object (result), secondly for sub element you have to call it again.

    public Dictionary<string,string> GetDictionaryByObject(object obj)
    {
        {
            var dict = new Dictionary<string, string>();
            foreach (var prop in obj.GetType().GetProperties())
            {
                if (prop.PropertyType.IsPrimitive || prop.PropertyType == typeof(string))
                {
                    dict.Add(prop.Name, prop.GetValue(obj).ToString());
                }
                else
                {
                    var subDict = GetDictionaryByObject(prop.GetValue(obj));
                    foreach (var subProp in subDict)
                    {
                        dict.Add($"{prop.Name}.{subProp.Key}", subProp.Value);
                    }
                }
            }
            return dict;
        }
    }
    

    Result:

    enter image description here