C# 如何将类转换为 Dictionary<string,string>?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9210428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert class into Dictionary<string,string>?
提问by Chintan
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 ?
现在的实际点是我可以将 Class 转换为 Dictionary 吗?
In Dictionary I want my class properties as KEYand value of particular property as VALUE
在字典中,我希望我的类属性为KEY,特定属性的值为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 ?
如何从特定类中获取属性列表?
采纳答案by Matías Fidemraizer
This is the recipe: 1 reflection, 1 LINQ-to-Objects!
这就是秘诀:1 次反射,1 次 LINQ 到对象!
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.
自从我发布这个答案以来,我已经检查过很多人发现它很有用。我邀请寻找这个简单解决方案的每个人检查另一个问答,我将它概括为一个扩展方法:将对象映射到字典,反之亦然。
回答by Bruno Costa
Here a example with reflection without linq:
这是一个没有 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();
回答by Jon
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"];
}
回答by joelc
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;
}
回答by FishFingers
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.
我想使用 JToken 添加反射的替代方法。您将需要检查两者之间的基准差异以查看哪个具有更好的性能。
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.
请注意,此方法最适合扁平类结构。
回答by Nguyen Minh Hien
Just a gift for someone only need a simple and flat Dictionary<String,String>not requiring hierarchy or deserialize back to an object like me
只是送给某人的礼物只需要一个简单而扁平的Dictionary<String,String>不需要层次结构或反序列化回像我这样的对象
private static readonly IDictionary<string, string> SPECIAL_FILTER_DICT = new Dictionary<string, string>
{
{ nameof(YourEntityClass.ComplexAndCostProperty), "Some display text instead"},
{ nameof(YourEntityClass.Base64Image), ""},
//...
};
public static IDictionary<string, string> AsDictionary(this object source, BindingFlags bindingAttr = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
{
if (source == null)
return new Dictionary<string, string> {
{"",""}
};
return source.GetType().GetProperties(bindingAttr).ToDictionary
(
propInfo => propInfo.Name,
propInfo => propInfo.GetValue(source, null).GetSafeStringValue(propInfo.Name)
);
}
public static String GetSafeStringValue(this object obj, String fieldName)
{
if (obj == null)
return "";
if (obj is DateTime)
return GetStringValue((DateTime)obj);
// More specical convert...
if (SPECIAL_FILTER_DICT.ContainsKey(fieldName))
return SPECIAL_FILTER_DICT[fieldName];
// Override ToString() method if needs
return obj.ToString();
}
private static String GetStringValue(DateTime dateTime)
{
return dateTime.ToString("YOUR DATETIME FORMAT");
}
回答by Vasya Milovidov
I hope this extension can be useful to someone.
我希望这个扩展对某人有用。
public static class Ext {
public static Dictionary<string, object> ToDict<T>(this T target)
=> target is null
? new Dictionary<string, object>()
: typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public)
.ToDictionary(
x => x.Name,
x => x.GetValue(target)
);
}

