Using the contents of a list of items as a string name

I am using C # and am making lists from responses to a sqlite query.

List1 contains a field with the name of the field in list2

List1[i].field = fieldname

      

I want to use the field name stored in List1[i].field

to access an element in List2

something like:

List2[ii].+List1[i].field+

      

I have no idea if it is possible this way in C #, I am relatively new to it and in fact am fond of my PHP knowledge where something like this works.

+3


source to share


1 answer


For this type of data structure, you usually use a dictionary (key / value pairs) to dynamically select properties of an object. For your specific example, this can be achieved with reflection, but it's not used very often as other structures make it easier to work with.

List2[ii].GetType().GetProperty(List1[i].field).GetValue(List2[ii], null);

      

Reflection is not the fastest type of solution, generally, and it is generally not very convenient to go in and maintain highly reflective code if it can be avoided.



Alternatively, you can use Linq to move List2 from a list of your object types to a list of dictionary objects so you can do something like List2[ii][List1[i].field]

to accomplish the same.

var listDictionaries = List2
    .Select(l => new Dictionary<string, object>()
    {
        new { "Prop1", l.Prop1 },
        new { "Prop2", l.Prop2 },
        new { "Prop3", l.Prop3 },
    }).ToArray();
listDictionaries[ii][List1[i].field];

      

+7


source







All Articles