Wednesday, September 2, 2015

Convert List<Object> to DataTable using FastMember in C#.Net

Recently, I got the requirement to convert the List<Object> to DataTable. The ad-hoc way, which we have been following to loop through the List and create the DataTable – which I don’t want to do. Therefore, I found a very good way by using FastMember. All you have to do is to download the FastMember from NuGet. Following are the steps below to download the Fastmember

 


 

Search for fastmember, and then install it.

 


 

After completing the installation, just include the FastMember namespace – and with the help of ObjectReader class we will be able to convert List to DataTabe.

 

IEnumerable<Customer> customerData = GetAllCustomers();

            if (customerData.Count() > 0)

            {

                using (DataTable table = new DataTable())

                {

                    using (var reader = ObjectReader.Create(customerData, "CustomerId","CustomerName", "CustomerAddress"))

                    {

                        table.Load(reader);

                    }

                }

            }

 

  IEnumerable<Customer> GetAllCustomers()

        {

            Customer[] customers = new Customer[]

        {

            new Customer { CustomerId = 1, CustomerName = "Ali", CustomerAddress = "Pakistan" },

            new Customer { CustomerId = 2, CustomerName = "Wakeel", CustomerAddress ="Pakistan" },

            new Customer { CustomerId = 3, CustomerName = "Anthony", CustomerAddress ="England" }

        };

            return customers;

        }

 

GetAllCustomers() will return the Sample data. I believe this is one of the efficient and quickest way to process the Data. I Hope you all must have enjoyed it after implementing this code :)