Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting different object lists into a DataTable using FastMember

Tags:

c#

I have written a method that converts a generic list to a DataTable using FastMember from NuGet.

This is my code:

public  DataTable ConvertGenericListToDataTable(List<CustomObject> inputList)
{
    var dt = new DataTable();
    using (var reader = ObjectReader.Create(inputList))
    {
         dt.Load(reader);
    }
    return dt;
}


var customObject = new List<CustomObject>();
var dt = ListToDataTable.ConvertGenericListToDataTable(customObject);

Which works fine. Customobject is a custom object i have created, i have several different lists that i want to pass to my method: List<CustomobjectA> or List<CustomobjectB> and so on. Its not much of a problem writing a method for every type of list i want to convert to a DataTable, but this could end in repeating the same lines of code over and over again, this is something i obviously want to prevent

I tried changing the parameter's type to List<object> and List<dynamic>. Then my code won't compile because: "The best overloadmethod match for ConvertGenericListToDataTable has some invalid arguments".

Is there a way i can pass a List of objects as a parameter without defining the exact type of the object ?

like image 937
Pim Avatar asked Oct 21 '22 04:10

Pim


1 Answers

What about having a generic ConvertGenericListToDataTable method?

public  DataTable ConvertGenericListToDataTable<T>(List<T> inputList)
{
}
like image 179
NeddySpaghetti Avatar answered Oct 30 '22 13:10

NeddySpaghetti