2

I have a lot of times thinking about converting example of class to Dictionary<String, String> where key is variable name(class field name) and value is variable current assigned value. So we have a simple class:

public class Student
{
    public String field1;
    public Int64 field2;
    public Double field3;
    public Decimal field4;

    public String SomeClassMethod1()
    {
        ...
    }
    public Boolean SomeClassMethod2()
    {
        ...
    }
    public Int64 SomeClassMethod1()
    {
        ...
    }
}

How I expect it will look like:

static void Main(String[] args)
{
    Student student = new Student(){field1 = "", field2 = 3, field3 = 3.0, field4 = 4.55m};
    Dictionary<String, String> studentInDictionary = ConvertAnyToDictionary<Student>(student);
}

public Dictionary<String, String> ConvertAnyToDictionary<T>(T value) where T:class
{
...
}

Any ideas about how to make it real? Thx a lot for any advices.

EDIT1: Expected result:

studentInDictionary[0] = KeyValuePair("field1", "");
studentInDictionary[1] = KeyValuePair("field2", (3).ToString());
studentInDictionary[2] = KeyValuePair("field3", (3.0).ToString());
studentInDictionary[3] = KeyValuePair("field4", (4.55m).ToString());
Maris
  • 4,608
  • 6
  • 39
  • 68
  • What is the expected output for that code? – Oscar Mederos Feb 27 '13 at 09:06
  • @Maris - if you think about it, JSON is a dictionary of strings, so what you want is very simmilar to a JSON Serializer. So don't reinvent the wheel if you don't really need it. – dutzu Feb 27 '13 at 09:07

3 Answers3

3

Here is how you can do it:

public static Dictionary<String, String> ConvertAnyToDictionary<T>(T value) where T : class {
    var fields = typeof(T).GetFields();
    var properties = typeof(T).GetProperties();

    var dict1 = fields.ToDictionary(x => x.Name, x => x.GetValue(value).ToString());
    var dict2 = properties.ToDictionary(x => x.Name, x => x.GetValue(value, null).ToString());

    return dict1.Union(dict2).ToDictionary(x => x.Key, x=> x.Value);
}

Edit: I'm taking in count both fields and properties there. If you will only be using properties, you can just use dict2.

You might want to take a look at the BindingFlags argument received by GetFields() and GetProperties() methods.

Oscar Mederos
  • 29,016
  • 22
  • 84
  • 124
1
 var proInfos = student.GetType().GetProperties();

          if(proInfos!=null)
             {
                   Dictionary<string,string> dict= new Dictionary<string, string>();


             foreach (var propertyInfo in proInfos)
             {
                var tv = propertyInfo.GetValue(currentObj, null);

                 if(tv!=null)
                 {
                    if(dict.ContainsKey(propertyInfo.Name))
                        continue;

                    dict.Add(propertyInfo.Name, tv.ToString());
                 }


                }
             }
TalentTuner
  • 17,262
  • 5
  • 38
  • 63
0

You can either serialize using already existing Serializers (Xml or JSON) or you can go about it using reflection.

Here is an example of how to get fields with reflection:

Not getting fields from GetType().GetFields with BindingFlag.Default

Community
  • 1
  • 1
dutzu
  • 3,883
  • 13
  • 19
  • I dont think serializing class to JSON/Xml, then deserializing it to the Dictionary is a good idea. The problem is not in getting all field names, but the problem is getting values assigned to the current examplar of the class fields. – Maris Feb 27 '13 at 09:13
  • @Maris I was thinking the resulting JSON would suffice, you actually need to obtain the final form of KeyValuePairs? If yes, then go the Reflection path. Obtain all fields as FieldInfo[] and extract from there the name and value. – dutzu Feb 27 '13 at 09:14