0

I have a class that converts a T List into a DataTable. And my problem is that I can not get the elements from the generic List T. T can be any model from entityFramework, like:

public class Test
    {
        public string userId { get; set; }
        public string email { get; set; }
        public string name { get; set; }
    }

So List T is equivalent to List Test

My code is:

public class ConvertListToDataTable<T>
    {
        public T Field;

        public DataTable ConvertTest<T>(List<T> item)
        {
            DataTable dT = new DataTable();

            foreach(T t in item)
            {
             // here I want to get the elements from T and put them into the DataTable
            }

            return dT;
        }
    }

I know how to procces the dataTable, but I don't know how to get the 'userId', 'email', 'name' from the list

florinaL
  • 93
  • 1
  • 9

2 Answers2

1

The reason why you cannot access just any property from an object of type T is because T could be literally anything - from a generics standpoint how can you know upfront what properties type T has?

If you happen to know that all objects are based on a common interface or base class then you could apply a generic constraint to your ConvertListToDataTable<T> class; this would allow the compiler to know upfront that some properties are available to that type at a base level.

But if you want to allow T to be any type at all then @MrFox is correct in that you would need to use Reflection to view the properties the type has at runtime and fill your DataTable that way.

Peter Monks
  • 4,219
  • 2
  • 22
  • 38
0

Reflection can solve this:

    public void Test(object t)
    {
        var properties = t.GetType().GetProperties();
        foreach (var p in properties)
        {
            dT.Columns.Add(new DataColumn(p.Name, p.PropertyType));
        }

        var row = dT.NewRow();
        int col = 0;
        foreach (var p in properties)
        {
            row[col++] = p.GetValue(t);
        }
    }

You can give the GetProperties method arguments if you only want properties of a certain type.

MrFox
  • 4,852
  • 7
  • 45
  • 81