Monday, May 17, 2010

Generic List to DataTable

In debug mode, we need sometimes to see the contents of Generic List like a table. By an intermediate of extension method, we converts a list of object to datatable


// Get Table from a generic List
public static DataTable getTable(this IList items)
{
if (items == null || items.Count == 0) return new DataTable();
DataTable dt = new DataTable();
DataColumn col;
IDictionary dic = null;
if (items.Count > 0)
{
dic = items[0].getDictionnary();
}
foreach (KeyValuePair kvp in dic)
{
col = new DataColumn(kvp.Key);
dt.Columns.Add(col);
}
DataRow row;
foreach (T item in items)
{
dic = item.getDictionnary();
row = dt.NewRow();
foreach (KeyValuePair kvp in dic)
{
row[kvp.Key] = kvp.Value;
}
dt.Rows.Add(row);
}
return dt;
}

The function "getDictionnary" use Reflexion to converts each Generic to a ditionnary:


// Iterate Object properties and get their values
public static IDictionary getDictionnary(this T obj)
{
// Puts the result as a dictionary whose key is the name of the attribute
IDictionary dic = new Dictionary();
// Get table infos from objet
PropertyInfo[] pInfo = (typeof(T)).GetProperties();
var val = from PropertyInfo p in pInfo
select p;

foreach (var v in val)
{
if (dic.ContainsKey(v.Name)) continue;
dic.Add(v.Name, v.GetValue(obj, null) == null ? string.Empty : v.GetValue(obj, null).ToString());
}
return dic;
}

Finally, we construct a list of book and call getTable function like this:


static void Main(string[] args)
{
IList books = new List();
books.Add(new Book { BookId = 4, Title = "العقد النفيس في نظم جواهر التدريس", PublicationDate = new DateTime(1780, 1, 1), Author = "سيدى أحمد بن إدريس" });
books.Add(new Book { BookId = 1, Title = "البحر المديد", PublicationDate = new DateTime(1804, 1, 1), Author = "سيدى ابن عجيبة الحسني"});
books.Add(new Book { BookId = 1, Title = "Animal Farm", PublicationDate = new DateTime(1945, 1, 1), Author = "Georges ORWELL" });
books.Add(new Book { BookId = 2, Title = "The Alchemist", PublicationDate = new DateTime(1988, 1, 1), Author = "Paulo Coelho" });
books.Add(new Book { BookId = 3, Title = "The Gulag Archipelago", PublicationDate = new DateTime(1973, 1, 1), Author = "Aleksandr Isayevich Solzhenitsyn" });
books.Add(new Book { BookId = 1, Title = "Le Comte de Monte-Cristo", PublicationDate = new DateTime(1918, 1, 1), Author = "Alexandre Dumas" });
//Get a DataTable
DataTable dt = books.getTable();
}

So in the debug mode, we can view the content of the Generic List like this:



In this article, we see how to visualize a Generic List in debug mode simply. I hope this will help you out.


zip GenericsToTable.zip - 28.5 Kio

No comments:

Post a Comment