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 :)

 


 

              

 

 

10 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Great Sharing! . Thank you so much it resolved my problem.

    ReplyDelete
  3. Hi Admin,
    Excellent blog and its totally loaded with valid posts on Java and .Net technology. Consider including RSS feed in your blog, so aspirants like me can follow your blog easily. .Net Training in Chennai

    ReplyDelete
  4. Great content thanks for sharing this informative blog which provided me technical information keep posting.
    java training in chennai

    ReplyDelete


  5. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Android Training in Chennai
    Ios Training in Chennai

    ReplyDelete