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
Convert List of Entity from Datatable
Mitesh Patel
Dec 21
2014
Code
3.1
k
0
0
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
expand
public
static
List<T> Convert<T>(DataTable dataTable)
{
List<T> lstEntity =
new
List<T>();
if
(dataTable ==
null
)
return
lstEntity;
Type classType =
typeof
(T);
PropertyInfo[] propertyInfos = classType.GetProperties();
if
(propertyInfos.Count() == 0)
return
lstEntity;
// there is no property to set value
List<DataColumn> columns = dataTable.Columns.Cast<DataColumn>().ToList();
foreach
(DataRow row
in
dataTable.Rows)
{
T t = Activator.CreateInstance<T>();
foreach
(PropertyInfo propertyInfo
in
propertyInfos)
{
Attribute[] attribs = Attribute.GetCustomAttributes(propertyInfo,
true
);
string
propertyName =
string
.Empty;
if
(attribs.ToList().IsNullOrEmpty())
propertyName = propertyInfo.Name;
else
propertyName = ((System.Xml.Serialization.XmlElementAttribute)(attribs[0])).ElementName;
DataColumn column = columns.Find(col => col.ColumnName == propertyName);
if
(column !=
null
)
propertyInfo.SetValue(t, (row[column].GetType().ToString().ToLower().Equals(
"system.dbnull"
) ?
null
: row[column]),
null
);
}
lstEntity.Add(t);
}
return
lstEntity;
}
C#
Datatable
List of Entity