Introduction
This tip will show you how to convert a DataRow
into an object with nullable properties.
Hope the code snippet below will help you.
Using the Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
public static class DataTableHelper
{
public static T ToObject<T>(this DataRow row) where T : class, new()
{
T obj = new T();
foreach (var prop in obj.GetType().GetProperties())
{
try
{
if(prop.PropertyType.IsGenericType && prop.PropertyType.Name.Contains("Nullable"))
{
if (!string.IsNullOrEmpty(row[prop.Name].ToString()))
prop.SetValue(obj, Convert.ChangeType(row[prop.Name],
Nullable.GetUnderlyingType(prop.PropertyType), null));
}
else
prop.SetValue(obj, Convert.ChangeType(row[prop.Name], prop.PropertyType),null);
}
catch
{
continue;
}
}
return obj;
}
public static List<T> DataTableToList<T>(this DataTable table) where T : class, new()
{
try
{
List<T> list = new List<T>();
foreach (var row in table.AsEnumerable())
{
var obj = row.ToObject<T>();
list.Add(obj);
}
return list;
}
catch
{
return null;
}
}
}