Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
597 views
in Technique[技术] by (71.8m points)

c# - How can I convert a class into Dictionary<string,string>?

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...