C#.Net dataTable to generic list.
How do you convert datatable to generic list in C#?
I had to work on an old project with many old web services, and all of them returns datatables, I want to show you a simple way of converting datatable to generic list.
Is an interesting workaround if you don’t want to change each web service or add more functions to return the same information.
The IEnumerable is a generic interface, and it defines a template that types can implement for looping.
The AsEnumerable is a generic method that helps you to implement to cast a specific type to its IEnumerable equivalent. (You can found the documentation here https://msdn.microsoft.com/en-us/library/system.data.datatableextensions.asenumerable(v=vs.110).aspx)
So you only have to follow the next steps :
Declare a variable as DataTable to store the original result of your old web service.
Then you have to declare IEnumerable SelectListItem that will be your final result.
The last step is to use the first variable that We declare as a datatable and use like AsEnumerable, and map your Id and Text values to your list.
//Generic list example
DataTable dt = GetCustomersDatatable(null);
IEnumerable<SelectListItem> lstCustomer = dt.AsEnumerable().Select(x => new SelectListItem()
Value = x.Field<string>(“CustomerId”),
Text = x.Field<string>(“CustomerDescription”)
This is an easy way to reconnect your old webservice and transform it in a Dynamic List.
For more information, you can check this link of MSDN forum
Thanks for reading!