How to Convert a Class into Dictionary<String,String>

How can I convert a class into Dictionarystring,string?

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

 someObject.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.ToDictionary(prop => prop.Name, prop => (string)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

Is there an easy way to convert object properties to a dictionarystring, string

Assuming that data is some object and that you want to put its public properties into a Dictionary then you could try:

Original - here for historical reasons (2012):

Dictionary<string, string> FD = (from x in data.GetType().GetProperties() select x)
.ToDictionary (x => x.Name, x => (x.GetGetMethod().Invoke (data, null) == null ? "" : x.GetGetMethod().Invoke (data, null).ToString()));

Updated (2017):

Dictionary<string, string> dictionary = data.GetType().GetProperties()
.ToDictionary(x => x.Name, x => x.GetValue(data)?.ToString() ?? "");

How to convert ListClass to Dictionarystring, ListString in C#?

Simply Call Linq's ToDictionary extension method for IEnumerable<T>, only condition is key for each element needs to be unique, or else it will fail since Dictionary wants a unique key

var tempDict = tempCollection.ToDictionary(x => x.key, x => x.values);

Convert nested class to dictionary

(Apologies, I dont have time to test this.)

You could write a solution using reflection and recursion. Something like this, below.

You will want to add null checks, and other exit cases otherwise you will quickly end up in an infinate loop.
This is just to get you started.

public Dictionary<string, string> MapToDictionary(object source, string name)
{
var dictionary = new Dictionary<string, string>();
MapToDictionaryInternal(dictionary, source, name);
return dictionary;
}

private void MapToDictionaryInternal(
Dictionary<string, string> dictionary, object source, string name)
{
var properties = source.GetType().GetProperties();
foreach(var p in properties)
{
var key = name + "." + p.Name;
object value = p.GetValue(source, null);
Type valueType = value.GetType();

if (valueType.IsPrimitive || valueType == typeof (String))
{
dictionary[key] = value.ToString();
}
else if (value is IEnumerable)
{
var i = 0;
foreach (object o in (IEnumerable) value)
{
MapToDictionaryInternal(dictionary, o, key + "[" + i + "]");
i++;
}
}
else
{
MapToDictionaryInternal(dictionary, value, key);
}
}
}

Call it like this:

Dictionary<string, string> dictionary2 = MapToDictionary(agreement, "Agreement");

How to convert Dictionarystring, object to Dictionarystring, string in c#

Use the ToDictionary method:

Dictionary<string, string> dString = dObject.ToDictionary(k => k.Key, k => k.Value.ToString());

Here you reuse the key from the original dictionary and you convert the values to strings using the ToString method.

If your dictionary can contain null values you should add a null check before performing the ToString:

Dictionary<string, string> dString = dObject.ToDictionary(k => k.Key, k => k.Value == null ? "" : k.Value.ToString());

The reason this works is that the Dictionary<string, object> is actually an IEnumerable<KeyValuePair<string,object>>. The above code example iterates through the enumerable and builds a new dictionary using the ToDictionary method.

Edit:

In .Net 2.0 you cannot use the ToDictionary method, but you can achieve the same using a good old-fashioned foreach:

Dictionary<string, string> sd = new Dictionary<string, string>(); 
foreach (KeyValuePair<string, object> keyValuePair in dict)
{
sd.Add(keyValuePair.Key, keyValuePair.Value.ToString());
}

Edit2:

If you are on .Net 2.0 and you can have null values in the dictionary the following should be safe:

Dictionary<string, string> sd = new Dictionary<string, string>(); 
foreach (KeyValuePair<string, object> keyValuePair in dict)
{
sd.Add(keyValuePair.Key, keyValuePair.Value == null ? "" : keyValuePair.Value.ToString());
}

Mapping object to dictionary and vice versa

Using some reflection and generics in two extension methods you can achieve that.

Right, others did mostly the same solution, but this uses less reflection which is more performance-wise and way more readable:

public static class ObjectExtensions
{
public static T ToObject<T>(this IDictionary<string, object> source)
where T : class, new()
{
var someObject = new T();
var someObjectType = someObject.GetType();

foreach (var item in source)
{
someObjectType
.GetProperty(item.Key)
.SetValue(someObject, item.Value, null);
}

return someObject;
}

public static IDictionary<string, object> AsDictionary(this object source, BindingFlags bindingAttr = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
{
return source.GetType().GetProperties(bindingAttr).ToDictionary
(
propInfo => propInfo.Name,
propInfo => propInfo.GetValue(source, null)
);

}
}

class A
{
public string Prop1
{
get;
set;
}

public int Prop2
{
get;
set;
}
}

class Program
{
static void Main(string[] args)
{
Dictionary<string, object> dictionary = new Dictionary<string, object>();
dictionary.Add("Prop1", "hello world!");
dictionary.Add("Prop2", 3893);
A someObject = dictionary.ToObject<A>();

IDictionary<string, object> objectBackToDictionary = someObject.AsDictionary();
}
}

C# Convert Liststring to Dictionarystring, string

Try this:

var res = list.ToDictionary(x => x, x => x);

The first lambda lets you pick the key, the second one picks the value.

You can play with it and make values differ from the keys, like this:

var res = list.ToDictionary(x => x, x => string.Format("Val: {0}", x));

If your list contains duplicates, add Distinct() like this:

var res = list.Distinct().ToDictionary(x => x, x => x);

EDIT To comment on the valid reason, I think the only reason that could be valid for conversions like this is that at some point the keys and the values in the resultant dictionary are going to diverge. For example, you would do an initial conversion, and then replace some of the values with something else. If the keys and the values are always going to be the same, HashSet<String> would provide a much better fit for your situation:

var res = new HashSet<string>(list);
if (res.Contains("string1")) ...


Related Topics



Leave a reply



Submit