Conversion of Generic List to DataSet

Niladri.biswas
Posted by Niladri.biswas under C# category on | Points: 40 | Views : 3870
Sometime we may need to convert a Generic List to a DataSet. Here is my solution that will help us to do so

public static class DataSetExtension
{
public static DataSet ToDataSet<T>(this List<T> list)
{
Type type = typeof(T);
DataSet ds = new DataSet();
DataTable dt = new DataTable(type.Name);
ds.Tables.Add(dt);

var propertyInfos = type.GetProperties().ToList();

//For each property of generic List (T), add a column to table
propertyInfos.ForEach(propertyInfo =>
{
Type columnType = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
dt.Columns.Add(propertyInfo.Name, columnType);
});

//Visit every property of generic List (T) and add each value to the data table
list.ForEach(item =>
{
DataRow row = dt.NewRow();
propertyInfos.ForEach(
propertyInfo =>
row[propertyInfo.Name] = propertyInfo.GetValue(item, null) ?? DBNull.Value
);
dt.Rows.Add(row);
});

//Return the dataset
return ds;
}
}


How to invoke it?
class Program
{
static void Main(string[] args)
{
List<Person> lstString = new List<Person>();
Enumerable.Range(1, 10).ToList().ForEach(i => lstString.Add(new Person { PersonId = i, PersonName = string.Concat("Name", i) }));

var res = lstString.ToDataSet();
}
}

public class Person
{
public int PersonId { get; set; }
public string PersonName { get; set; }
}

Comments or Responses

Login to post response