C# list to datatable Edit

Murugan Andezuthu Dharmaratnam | 23 September 2020 | 697

In this post, we will write code to convert a list to a datatable. Here in the code I am creating a list of RecipeIngredients and below I have provided an extension method to convert the list of RecipeIngredients to DataTable.

List lstRecipeIngredients= new List()
    new RecipeIngredients() { IngredientName="Mango", Quantity="10", UnitName="Kg" },
    new RecipeIngredients() { IngredientName="Coconut", Quantity="1", UnitName="Number" },
    new RecipeIngredients() { IngredientName="Chillies", Quantity="2", UnitName="Table Spoon" }

DataTable dtRecipeIngredients = lstRecipeIngredientsSP.ToDataTable();
dtRecipeIngredients.TableName = "RecipeIngredients";


public static partial class SqlExtensions
    public static DataTable ToDataTable(this List items)
        DataTable dataTable = new DataTable(typeof(T).Name);

        //Get all the properties
        PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (PropertyInfo prop in Props)
            //Defining type of data column gives proper data table 
            var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
            //Setting column names as Property names
            dataTable.Columns.Add(prop.Name, type);
        foreach (T item in items)
            var values = new object[Props.Length];
            for (int i = 0; i < Props.Length; i  )
                //inserting property values to datatable rows
                values[i] = Props[i].GetValue(item, null);
        //put a breakpoint here and check datatable
        return dataTable;