遍历字典并使用值遍历C#类

时间:2020-06-18 12:34:08

标签: c# class dictionary

在我的C#代码中,我在Dictionary上进行了迭代,并希望使用Classes

MyModel othermodel = new MyModel();

Dictionary<string, string> mydictionary = new Dictionary<string, string>()
{
    {"n1", "Item"},
    {"n2", "Second"},
    {"n3", "Third"},
    {"n4", "Fourth"},
    {"n5", "Fith"},
    {"n6", "Sixth"},
    {"n7", "Seventh"},
    {"n8", "Eighth"},
    {"n9", "Ninth"},
    {"n0", "Tenth"},
    {"n11", "Eleventh"}

};

foreach (var dicitem in mydictionary.ToArray())
{
    foreach (MyModel.NewItem.(mydictionary[dicitem].Value) item in othermodel.(mydictionary[dicitem].Key))
    {
         ...
    }
}

所以我的结果是:

first iteration:

foreach (MyModel.NewItem.Item item in othermodel.n1)
{
     ...
}

second iteration:

foreach (MyModel.NewItem.Second item in othermodel.n2)
{
     ...
}

...

如果有办法,将不胜感激。

1 个答案:

答案 0 :(得分:0)

可以使用反射来通过名称访问对象属性,而与这些名称的来源(字典,数组等)无关紧要

这里的小例子:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

然后访问您执行的Name属性:

var me = new Person {Name = "John", Age = 33};

var propertyName = "Name";
var propertyInfo = typeof(Person).GetProperty(propertyName);

var propertyValue = propertyInfo?.GetValue(me) as string;

使用上层代码创建一个Propertynfo。

如果要读取同一对象的更多属性,最好一次读取所有PropertyInfo对象:

var me = new Person {Name = "John", Age = 33};

var propertiesInfo = typeof(Person).GetProperties();

var propertyName = "Name";
var nameProperty = propertiesInfo
    .Single(p => p.Name == propertyName);
var name = nameProperty.GetValue(me) as string;


//faster approach
var age = (int)propertiesInfo
    .Single(p => p.Name == "Age")
    .GetValue(me);

请注意,在此示例中,我假设存在具有特定名称的属性,因此我简单地称为Single。但是,在不同的情况下,可能需要您在访问属性之前先检查属性的存在。