简体   繁体   中英

Iterate through a dictionary and use value to iterate through class C#

In my c# code, I have an iteration over a Dictionary and want to achieve something like so using 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))
    {
         ...
    }
}

So my result would be:

first iteration:

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

second iteration:

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

...

If there is a way to do this, any help would be appreciated.

Accessing object properties via its names can be done using Reflection, doesn't matter where these names come from (dictionary, array, ...)

Little example here:

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

then to access the Name property you do:

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

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

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

Using the upper code, you create one Propertynfo.

If you want to read more properties of the same object, it is better to read all PropertyInfo objects at once:

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);

Be be aware that in this example, I suppose that the property with specific name exists, so I simply called Single . In different situation however, it may require you to check the existence of property before accessing it.

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