Header add

In this article we will learn about How to convert LINQ query result to DataTable using C#. For example we have the List of Customers and we want to extract this customers using Linq and convert the result to datatable in C#. Following below steps we can achieve that. Please read our all C# articles here.

Step-1

Let's first create the Model that hold the Customer details like below,


Create another Model class that will responsible to convert Linq result to DataTable.
  • A DataTable is created by determining the name of the Class.
  • Then the properties of the Class are read and then Columns are created in the DataTable after determining the names of the properties.
  • Now, a loop is executed over the items of the IEnumerable collection and inside the loop, a DataRow is created with values and added to the DataTable and it returned.


Step-2

On below we added some dummy data into List<customer> and using Linq query we extract and call the convert method to use in dataTable.



Output

Now debug the application we can see in debug visualizer the result like below. On the next article we can see how to display it in Gridview.

linq-to-datatable


Post a Comment

Previous Post Next Post