0

I have foreach code block in a method, I'm using this many places.

"Title" is a String type property of "UsefulLinks" class which I mention "Before". But I want to assign that property with my String variable which is fieldName. How can we reach an instance and assign its value?

Before:

        foreach (var item in vm.UsefulLinks)
        {
            item.Title = usefullLinkTranslations
                .LastOrDefault(t => t.FieldName == fieldName)
                ?.Value;
        }

After:

        foreach (var item in vm.UsefulLinks)
        {
            item.["fieldName"]= usefullLinkTranslations
                .LastOrDefault(t => t.FieldName == fieldName)
                ?.Value;
        }
Eby Jacob
  • 1,418
  • 1
  • 10
  • 28
kirelli
  • 29
  • 4

2 Answers2

1

Either build a switch statement for each property you want to support:

foreach (var item in vm.UsefulLinks)
{
    var fieldValue = usefullLinkTranslations.LastOrDefault(t => t.FieldName == fieldName)?.Value;

    switch (fieldName)
    {
        case "Title":
            item.Title = fieldValue;
            break;
        case "Name":
            item.Name = fieldValue;
            break;
        // ...
    }

}

Or use reflection to assign the property.

smile
  • 78
  • 7
0

You can use reflection (@smile mentioned) like this;

var type = typeof(UsefulLinks);
foreach (var item in vm.UsefulLinks)
{
    type.GetProperty(fieldName) // GetField for fields
         .SetValue(
             item, 
             usefullLinkTranslations
                 .LastOrDefault(t => t.FieldName == fieldName)
                 ?.Value
         );
}
Umut Özel
  • 354
  • 5
  • 17