创建具有类属性的列表

时间:2020-06-09 09:03:19

标签: c#

我的课具有一些基本类型的属性和一个字典,例如:

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()
    {
    }
}

现在,我想创建一个包含所有属性名称的列表,然后执行以下操作:

                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?
                    }
                }

如何遍历我的字典?

1 个答案:

答案 0 :(得分:1)

您可以直接使用DataDictionary并如此进行迭代。

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