1

I have a generic object containing a list with objects, which I like to access. By using

object sourceValue = new List<tab> {new tab()};
PropertyInfo[] sourcePropertyInfo = sourceValue.GetType().GetProperties();
//First field of PropertyInfo is the list, second is a Raw instance
object result = sourcePropertyInfo[0].GetValue(sourceValue, null);

Where the tab object looks like this:

public partial class tab
{
    public long TabId { get; set; }
    public string Title { get; set; }
}

Here I would like to access the list throught the result variable but it results in result = 0, which is an integer. Most likley it takes the count property from the list. How can I access the values in the objects in the list (of type tab)?

Note, I can not access or change the type of the object sourceValue.

romain-aga
  • 1,441
  • 9
  • 14
  • The first field of your `PropertyInfo`-array is neither the list itself nor any instance within it, is is the first property of the type `List`, which is probably the `Count`-property. I suppose you´re asking a completely different question actually, this seems like an XY-problem, where you´re thinking this is the solution to your actual problem, have a problem on this solution where you should solve your *actual* one instead. – MakePeaceGreatAgain Oct 07 '16 at 09:20
  • 2
    I don't understand why you are using `reflection` here, you don't need to. Just cast `sourceValue` into `List` and it should works. – romain-aga Oct 07 '16 at 09:21
  • 1
    This following link may helpful to you http://stackoverflow.com/questions/10710156/using-reflection-to-get-values-from-properties-from-a-list-of-a-class – Vaibhav Bhatia Oct 07 '16 at 09:27

1 Answers1

5

You are getting properties of list type, not the type of elements.

foreach (object element in (sourceValue as IEnumerable ?? Enumerable.Empty<object>()))
{
   var type = element.GetType();
   var props = type.GetProperties();
   object result = props.First().GetValue(element, null);
}

Note: this can be optimized :)

pwas
  • 3,225
  • 18
  • 40