Swag
Swag

Reputation: 2140

Iterate object list and get element property with a string

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.

Upvotes: 2

Views: 1553

Answers (2)

Antonio
Antonio

Reputation: 72810

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

Upvotes: 1

khellang
khellang

Reputation: 18132

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

Upvotes: 5

Related Questions