-2

I'm using the following method to enumerate fields of my classes-

EnumerateFields(typeof(Student));

void EnumerateFields(Type type)
{
    PropertyInfo[] props = type.GetProperties();
    foreach (PropertyInfo prp in props)
    {

    }
}

It works nicely.

Now I would like to do the same task from a List<>. Pseudo code-

EnumerateFields(List<Student>);

void EnumerateFields(List<T>)
{

}

Is there any way to do it?

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
s.k.paul
  • 7,099
  • 28
  • 93
  • 168

2 Answers2

2

I assume you want something like this:

void EnumerateFields<T>(List<T> input)
{
    PropertyInfo[] props = typeof(T).GetProperties();
    foreach (var r in input)
    {    
        foreach (PropertyInfo prp in props)
        {
            Console.WriteLine(prp.Name + " = " + prp.GetValue(r));
        }
    }
}
sgmoore
  • 15,694
  • 5
  • 43
  • 67
0

If you're sure, you're passing in List<T>, you can still get the properties of T as:

private void EnumerateFields(Type type)
{
    Type subType = type.GetGenericArguments()[0];

    PropertyInfo[] props = subType.GetProperties();
    foreach (PropertyInfo prp in props)
    {
        // your logic here
    }
}
Peter Szekeli
  • 2,712
  • 3
  • 30
  • 44