Convert Generic List to Dataset in C# | Easy Solution
If you are working with C# and need to convert a generic list to a dataset, there is an easy solution that you can use to accomplish this task.
To start, you will need to create a new DataTable
object and add the appropriate columns to it. You can use the properties of the objects in your generic list to determine the structure of your DataTable
, or you can define the columns manually.
Once you have your DataTable
set up, you can create a new DataSet
object and add your DataTable
to it. You can then use a foreach
loop to populate the DataTable
with data from your generic list.
Here is some sample code that you can use to accomplish this task:
List<MyObject> myList = GetMyList();
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Description", typeof(string));
foreach (MyObject obj in myList)
{
DataRow dr = dt.NewRow();
dr["ID"] = obj.ID;
dr["Name"] = obj.Name;
dr["Description"] = obj.Description;
dt.Rows.Add(dr);
}
DataSet ds = new DataSet();
ds.Tables.Add(dt);
Once you have completed these steps, you will have successfully converted your generic list to a dataset. This solution is easy to implement and will allow you to work with your data in a variety of ways.
Leave a Reply
Related posts