andyh0316
andyh0316

Reputation: 355

Reflection: how to get values from object as List<object>

Using reflection, I need a function that accepts a list of generic objects and print its values

List<Gender> genders = new List<Gender> {
    new Gender {
        Id: 1,
        Name: "Male"
    },
    new Gender {
        Id: 2,
        Name: "Female"
    }
}

PrintListValues(genders, "Name"); // prints Male, Female

PrintListValues has to accept a list as object. And the list can contain any type of object. As long as the generic object have the property passed in, it should print the value of each item in list.

public static void PrintValues(object listObject) 
{
     // code here
} 

Unfortunately that's the way the project requirement is.

Been scratching my head over this one and can't figure it out. Reflection is too difficult for me. If anyone can give me hint that would be great!

Upvotes: 0

Views: 455

Answers (2)

TheGeneral
TheGeneral

Reputation: 81493

You likely just need

var values = anyList.Select(x => x.SomeProperty);

Console.WriteLine(string.Join(Environemnt.NewLine,values));

However if you really need to include a string property name

public IEnumerable<object> GetValues<T>(IEnumerable<T> source, string name)
{
   var prop = typeof(T).GetProperty(name) ?? throw new ArgumentNullException("typeof(T).GetProperty(propName)");
   return source.Select(x => prop.GetValue(x));
}

...

foreach (var value in GetValues(someList,"SomeProperty"))
   Console.WriteLine(value);

// or 

Console.WriteLine(string.Join(Environemnt.NewLine,GetValues(someList,"SomeProperty"));

Upvotes: 1

Ivan Vargas
Ivan Vargas

Reputation: 703

Try this:

public static void PrintListValues(IEnumerable<object> seq, string propName)
{
   foreach (var obj in seq)
   {
      var type = obj.GetType();
      var prop = type.GetProperty(propName);
      var value = prop.GetValue(obj);
      Console.WriteLine(value);
   }
}

Disclaimer: To play with reflection, the above code is fine. For a real world situation, there might be a few things to check as that code assumes the "happy path".

Upvotes: 1

Related Questions