如何将类转换为Dictionary< string,string&gt ;? [英] How can I convert a class into Dictionary<string,string>?

查看:248
本文介绍了如何将类转换为Dictionary< string,string&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以将Class转换成Dictionary< string,string>吗?

Can I convert Class into Dictionary<string, string>?

在Dictionary中,我希望将类属性作为 keys 并将特定属性的值作为

In Dictionary I want my class properties as keys and value of particular a property as the 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

现在您可以

我想制作字典!该字典应该像这样:

I want to make a 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 a list of properties from particular class?

现在,我再次解释我对Dictionary的渴望之一!我的上一个问题 !!

Now again I am explaining one of my eagernesses about Dictionary! This question popuped in my mind from answer of my previous question!!

推荐答案

这是配方:1个反射,1个LINQ-to-Objects!

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,并将其概括为扩展方法:将对象映射到字典,反之亦然

这篇关于如何将类转换为Dictionary&lt; string,string&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆