Please help me to convert below "Order" object into dictionary.
public class Order
{
#region Properties
public byte? IsMarried
{
get;
set;
}
public byte? IsEmployed
{
get;
set;
}
public byte? IsStudent
{
get;
set;
}
public string Name
{
get;
set;
}
}
----------------------
public class OrderManager : Order
{
private Dictionary<string, object> preferences;
}
How can i convert order object as dictionary(Key/Value pair) in OrderManager class.
public static class ObjectToDictionaryHelper
{
public static IDictionary<string, object> ToDictionary(this object source)
{
return source.ToDictionary<object>();
}
public static IDictionary<string, T> ToDictionary<T>(this object source)
{
if (source == null) ThrowExceptionWhenSourceArgumentIsNull();
var dictionary = new Dictionary<string, T>();
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(source))
{
object value = property.GetValue(source);
if (IsOfType<T>(value))
{
dictionary.Add(property.Name, (T)value);
}
}
return dictionary;
}
private static bool IsOfType<T>(object value)
{
return value is T;
}
private static void ThrowExceptionWhenSourceArgumentIsNull()
{
throw new NullReferenceException("Unable to convert anonymous object to a dictionary. The source anonymous object is null.");
}
}
MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue.
If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.
Member
19 Points
35 Posts
How to convert object into Dictionary
Mar 13, 2018 05:21 AM|chandu_king|LINK
Hello All,
Please help me to convert below "Order" object into dictionary.
How can i convert order object as dictionary(Key/Value pair) in OrderManager class.
Thanks in Advance,
Chandu
Contributor
2842 Points
767 Posts
Re: How to convert object into Dictionary
Mar 13, 2018 06:31 AM|mshoaiblibra|LINK
As per you query, I recommend you already discussed thread on same topic.
how to convert an object of Item to an dictionary not idictionary in c#
Other Refer Link:
https://gist.github.com/jarrettmeyer/798667/a87f9bcac2ec68541511f17da3c244c0e05bdc49
M Shoaib Waheed
MCSD & MCPD [Web Development 4.0]
http://shoaib.pk
Contributor
6711 Points
2334 Posts
Re: How to convert object into Dictionary
Mar 13, 2018 10:02 AM|cnranasinghe|LINK
Have a look below,
Star
8670 Points
2882 Posts
Re: How to convert object into Dictionary
Mar 14, 2018 02:00 AM|Cathy Zou|LINK
Hi chandu_king
Related code as below:
Related links:
https://stackoverflow.com/a/13602785/9143922
https://gist.github.com/jarrettmeyer/798667/a87f9bcac2ec68541511f17da3c244c0e05bdc49
Best regards
Cathy
Please remember to click "Mark as Answer" the responses that resolved your issue.
If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.