如何类转换成字典&LT;字符串,字符串&GT ;? [英] How to convert class into Dictionary<string,string>?
问题描述
现在我再次解释我对词典的渴望之一!这个问题是在我的脑海popuped从我的 previous问题!
Now again I am explaining one of my eagerness about Dictionary ! This question is popuped in my mind from answer of my previous question !!
现在的实际问题是的我可以转换成类词典?
在字典我想我的类属性的 KEY 并特定财产作为价值的值
In Dictionary I want my class properties as KEY and value of particular property as VALUE
假如我的类是
public class Location
{
public string city { get; set; }
public string state { get; set; }
public string country { get; set;
}
现在假设我的数据是
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");
我可以得到价值!但是,我怎么能得到属性的名称(不是值)?
我应该怎么code来创建它的动态!应为,我想每个班级工作?
的你可以理解这个问题,因为的
我怎样才能从特定的类属性的列表?
推荐答案
这是配方:1反射,1 LINQ到对象!
This is the recipe: 1 reflection, 1 LINQ-to-Objects!
someObject.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.ToDictionary(prop => prop.Name, prop => prop.GetValue(someObject, null))
的自从我发表这个答案我已经签,很多人发现它是有用的。我邀请大家寻找这个简单的解决方案来检查另一个Q&安培; A,我概括它变成一个扩展方法:<一href=\"http://stackoverflow.com/questions/4943817/mapping-object-to-dictionary-and-vice-versa/4944547#4944547\">Mapping对象字典,反之亦然。的
这篇关于如何类转换成字典&LT;字符串,字符串&GT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!