On many WPF or WinForms applications, when it comes to display data into a table, we are using DataTable class. Recently, I worked on a ASP.NET MVC Backend, where my source was a DataTable and I had to return an IEnumerable<T> to be consumed by a mobile app using Swagger and NSwag Studio. I wanted something simple and efficient to convert my table into an IEnumerable, I had that line of code in mind: myTable[“Users”].ToEnumerable<User>();

And here is my custom implementation, let’s start with how to use it:

The implementation of this class is available on my GitHub.

Let’s dig under the wood. The basic of this logic is mapping the User object with the name of the columns from the DataTable by using C# reflection so we will be able to make the conversion.

The implementation of this class is available on my GitHub.

UserNameCode and GroupCode are column names from a table and USER_TABLE is the name of that table. I could have used the DisplayNameAttribute attribute available in the .NET Framework, but the code could used it or will use it for another purpose. I think it’s better to create our own attribute.

The code of that custom attribute is on my GitHub.

Now here is the magic to convert a DataTable into an IEnumerable<T> :

The implementation of this class is available on my GitHub. If you copy / paste my code, you will need the IsNonStringEnumerable.

And here the opposite to convert an IEnumerable<T> into a DataTable:

The implementation of this class is available on my GitHub.

Here, one more method to convert a DataSet into an XML:

The whole project is available on my GitHub. If you have some bug fixes or interesting updates, please make a pull request. Thank you for reading and feel free to give me a little feedback :)