简体   繁体   中英

Create a list with class properties

My class has some properties with base type and a dictionary as:

public class Statistic
{
    public int Id { get; set; }
    public object Parent { get; set; }
    public bool IsExpanded { get; set; }
    public string Data { get; set; }
    public string Code { get; set; }
    public Dictionary<string, object> DataDictionary { get; set; } = new Dictionary<string, object>();

    public Statistic()
    {
    }
}

Now I want to create a list with all the properties' name and I did this:

                List<string> columns = new List<string>();

                PropertyInfo[] properties = typeof(Statistic).GetProperties();
                foreach (PropertyInfo property in properties)
                {
                    columns.Add(property.Name);
                    if (property.Name=="DataDictionary")
                    {
// How to iterate thru my Dictionary?
                    }
                }

How to iterate thru my dictionary?

You can directly use the DataDictionary and iterate like this.

foreach(KeyValuePair<string, object> kvp in DataDictionary)
{
    // use the kvp.Value and kvp.Key
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM