2

I am looking for a solution to solve this problem I have.

I got an Object:

- Person (String ID, String FirstName, String LastName)

I got a List with a couple Persons

- List<Person> persons;

What my goal is:

1. Iterate through List
2. Get property value from that element with a string named to that property

For example:

I want to know the ID of the person in a list:

I can do this:

foreach(Person p in persons)
{
    String personId = p.ID;
}

But I want to do something like this:

foreach(Person p in persons)
{
    String personId = p. + "ID";
}

I want to append the string "ID" to get the ID of that element, instead of calling p.ID.

Is this possible? I need a solution for this, and I have spent a lot of time but couldn't find any solution on the internet.

7
  • 2
    Why would you want to do that? Commented Mar 24, 2014 at 10:54
  • 1
    You should use reflection, take a look at this SO question. Commented Mar 24, 2014 at 10:54
  • @khellang I am reading a text file with ID's and Property names. I am getting the persons by their ID (read from the file) and put them in a list. Then I read the property names (string) from that file and iterate through the list that I've filled and get the property value of the element by the read strings from the file. Commented Mar 24, 2014 at 10:56
  • 1
    @AlessandroD'Andria: 99.9999999% of all questions that can be solved with reflection are just the wrong approach. If OP would say what he's actually trying to do we could help to find a better approach. Commented Mar 24, 2014 at 10:57
  • @TimSchmelter i am not a big fan of reflection, but for what the OP is asking it's the only way, but you're right that the OP have to move a few steps back and rethink it's problem. Commented Mar 24, 2014 at 11:02

2 Answers 2

5

You could use reflection to get the value of a property by name:

foreach (Person p in persons)
{
    var personId = typeof(Person).GetProperty("ID").GetValue(p, null) as string;
}

Of course this needs some error handling and some null checks, but you get the gist :)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer. So getting the property value by a string is called Reflection in c#?
@y451n Yes. You can read about Type.GetProperty here.
1

As mentioned by other answers, the easiest way (although maybe not the best approach) is using reflection.

I've included support for base data types and string in the following class (and added an additional property to demonstrate how it can be used for base data types):

public class Person {
    public string ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }

    private PropertyInfo GetProperty(string name) {
        PropertyInfo property = GetType().GetProperty(name);

        if (property == null) {
            throw new ArgumentException(string.Format("Class {0} doesn't expose a {1} property", GetType().Name, name));
        }

        return property;            
    }

    public string GetStringProperty(string name) {
        var property = GetProperty(name);
        return (string) property.GetValue(this, null);
    }

    public T GetProperty<T>(string name) {
        var property = GetProperty(name);
        return (T) property.GetValue(this, null);
    }
}

The GetProperty and GetStringProperty methods throw a ArgumentException if the property doesn't exist.

Sample usage:

Person person = new Person {
    ID = "1",
    FirstName = "First",
    LastName = "Last",
    Age = 31            
};

Console.WriteLine(person.GetStringProperty("FirstName"));
Console.WriteLine(person.GetProperty<int>("Age"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.