Search code examples
c#datatablelisfastmember

FastMember ObjectReader Returns 0 results


I am using FastMember Library to convert List of objects to a dataTable but it returns empty object so could anyone help me to resolve this issue

List<object> list = new List<object>() { new { Number = 500 } };
DataTable table = new DataTable();
using (var reader = ObjectReader.Create(list))
{
    table.Load(reader);
}

Solution

  • Apparently, Fastmember is not able to enumerate the properties off of anonymous objects. Therefore, the created data reader has no columns and DataTable.Load method refuses to create empty rows for this reader.

    Try it with a concrete class if you can:

    class Thingy
    {
        public int Number { get; set; }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            List<Thingy> list = new List<Thingy>() { new Thingy { Number = 500 } };
            DataTable table = new DataTable();
            using (var reader = ObjectReader.Create(list))
            {
                table.Load(reader);
            }
        }
    }
    

    Edit: Actually, Fastmember is perfectly capable of accessing those properties, but the type of the generic List (object) prevents it from seeing them. It should also work if you can provide an IEnumerable with the actual runtime type:

    //This creates a "strongly" typed list, instead of List<object>:
    var list = new[] { (new { Number = 500 }) }.ToList();
    
    DataTable table = new DataTable();
    using (var reader = ObjectReader.Create(list))
    {
        table.Load(reader);
    }
    

    Edit 2: There is yet another way to pass the type information to Fastmember by using the constructor:

    List<object> list = new List<object> { new { Number = 500 } };
    
    DataTable table = new DataTable();
    
    // Note that type information is derived directly from the first object in the list, 
    // so try not to pass an empty one :)
    using (var reader = new ObjectReader(list[0].GetType(), list, null))
    {
        table.Load(reader);
    }
    

    Also note that this is riskier than the other approaches because it is possible to create a list with mixed item types. Fastmember needs every single item in the list to be of the exact same type and something like the following will cause an exception:

    //These two items are not of the same type. Look carefully at the "Extra" property:
    List<object> list = new List<object> { new { Number = 500, Extra = true }, new { Number = 500, Extra = "Boom" } };