TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Converting Collection to Dataset
Arunava Bhattacharjee
Aug 29, 2014
83.9
k
0
0
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
In this post you will learn how to convert a List of objects to a DataSet.
Introduction
I saw there is always a need to convert a list to a dataset and then bind it to a datagrid. To make it reusable I used the C# extension method feature.
Solution
We first check to make sure a list is provided or we throw an ArgumentNullException (in the overloaded constructor we also check for the name parameter). Here’s how the two constructors look:
public
static
DataSet ConvertToDataSet<T>(
this
IEnumerable<T> source,
string
name)
{
if
(source ==
null
)
throw
new
ArgumentNullException(
"source "
);
if
(
string
.IsNullOrEmpty(name))
throw
new
ArgumentNullException(
"name"
);
var converted =
new
DataSet(name);
converted.Tables.Add(NewTable(name, source));
return
converted;
}
Where Name= Name of the DataTable to be added to the DataSet.
Let’s have a look of the NewTable method:
private
static
DataTable NewTable<T>(
string
name, IEnumerable<T> list)
{
PropertyInfo[] propInfo =
typeof
(T).GetProperties();
DataTable table = Table<T>(name, list, propInfo);
IEnumerator<T> enumerator = list.GetEnumerator();
while
(enumerator.MoveNext())
table.Rows.Add(CreateRow<T>(table.NewRow(), enumerator.Current, propInfo));
return
table;
}
Here’s how CreateRow looks like:
private
static
DataRow CreateRow<T>(DataRow row, T listItem, PropertyInfo[] pi)
{
foreach
(PropertyInfo p
in
pi)
row[p.Name.ToString()] = p.GetValue(listItem,
null
);
return
row;
}
and the Table<T> method used in NewTable method:
private
static
DataTable Table<T>(
string
name, IEnumerable<T> list, PropertyInfo[] pi)
{
DataTable table =
new
DataTable(name);
foreach
(PropertyInfo p
in
pi)
table.Columns.Add(p.Name, p.PropertyType);
return
table;
}
Use
So now lets take a look at using this to convert a Generic list into a DataSet. In this example we will create a simple Generic list which will contain only 2 items, we will then use the Extension we created to convert the list into a DataSet:
var list =
new
List<Person>();
list.Add(
new
Person { ID = 1, Name =
"Arunava"
});
list.Add(
new
Person { ID = 2, Name =
"Bubu"
});
DataSet converted = list.ConvertToDataSet(
"TestTable"
);
Hope this helps.
Converting Collection to Dataset
Next Recommended Reading
Read and Import Excel File into DataSet or DataTable using C# in ASP.NET