C# Find Property Name and then set the value of the property

I am trying to loop through a collection that has three fields in each row of the collection. I want to set the property of my view model based on one of the fields in my collection. See before for an example.

//Collection ViewModel
 public class TestSubmissionViewModel
    {
        public string label { get; set; }
        public string val { get; set; }
        public string fieldType { get; set; }
    }

//My view model I want to populate
public class MyViewModel
{
public string name {get; set;}
public string address {get; set;}
public string address1 {get; set;}
}

In my TestSubmissionViewModel collection I will have values like:
label = "name", val="TestUser", fieldtype="String"
label = "address", val="111 Test St", fieldtype=String"

So I want to loop there the TestSubmissionViewModel and match up the "label" field value to the property of the MyViewModel and then set the value of that property. How can I do this?
nmiller61Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Nitin SontakkeDeveloperCommented:
Reflection (google it with word C#) is what you are looking for. Having said that I would strongly discourage you taking that path, unless you have a real strong business case for the support of such kind of coding.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
it_saigeDeveloperCommented:
Just to give you and idea of what Nitin is referring to with regards to reflection.  Here is one way you could do it:
static class Extensions
{
    public static T CopyTo<T>(this TestSubmissionViewModel source, T target) where T : class, new()
    {
        var t_prop = typeof(T).GetProperty(source.Label, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase);
        if (t_prop != null && t_prop.CanWrite)
        {
            try
            {
                t_prop.SetValue(target, source.Value);
            }
            catch (Exception)
            {
                // There was a problem setting the value of the property 
                // in the target object.  Log it, handle it or both.
            }
        }
        return target;
    }
}

Open in new window

Example usage -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace EE_Q29088474
{
    class Program
    {
        static readonly Dictionary<int, List<TestSubmissionViewModel>> contacts = (from i in Enumerable.Range(0, 5)
                                                                                   select new KeyValuePair<int, List<TestSubmissionViewModel>>(i, 
                                                                                       (from j in Enumerable.Range(0, 3)
                                                                                        select new TestSubmissionViewModel {
                                                                                            Label = j % 3 == 0 ? $"Address2" : j % 2 == 0 ? $"Address" : $"Name",
                                                                                            Value = j % 3 == 0 ? $"Address_2_{i}" : j % 2 == 0 ? $"Address_{i}" : $"Name_{i}",
                                                                                            FieldType = "String"
                                                                                        }).ToList())).ToDictionary(k => k.Key, v => v.Value);
        static void Main(string[] args)
        {
            var viewContacts = new List<MyViewModel>();
            foreach (var contact in contacts)
            {
                var view = new MyViewModel();
                foreach (var value in contact.Value)
                {
                    value.CopyTo(view);
                }
                viewContacts.Add(view);
            }

            Console.WriteLine(string.Join($"{Environment.NewLine}{Environment.NewLine}", viewContacts));
            Console.ReadLine();
        }
    }

    class MyViewModel
    {
        public string Name { get; set; }
        public string Address { get; set; }
        public string Address2 { get; set; }
        public override string ToString()
        {
            return $"{Name}{Environment.NewLine}{Address}{Environment.NewLine}{Address2}";
        }
    }

    class TestSubmissionViewModel
    {
        public string Label { get; set; }
        public string Value { get; set; }
        public string FieldType { get; set; }
    }

    static class Extensions
    {
        public static T CopyTo<T>(this TestSubmissionViewModel source, T target) where T : class, new()
        {
            var t_prop = typeof(T).GetProperty(source.Label, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase);
            if (t_prop != null && t_prop.CanWrite)
            {
                try
                {
                    t_prop.SetValue(target, source.Value);
                }
                catch (Exception)
                {
                    // There was a problem setting the value of the property 
                    // in the target object.  Log it, handle it or both.
                }
            }
            return target;
        }
    }
}

Open in new window

Which produces the following output -Capture.PNG
-saige-
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.