C# list to datatable Edit
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.
ListlstRecipeIngredients= 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";
Code
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); } dataTable.Rows.Add(values); } //put a breakpoint here and check datatable return dataTable; } }