Converting DataTable into Generic List

Posted by Mouli under C# category on | Views : 11817
Below method can be used to convert data from the DataTable into a Generic List <T>. First convert the DataTable in to an XML representation before using the method. Method to convert the DataTable to XML is also given below. Method makes following assumeptions.
1. Object exposes the mutators and accessors to set the value to the field members
2. Name of the property and Xml Node Name will be same.

This uses System.Reflection package members to loop through the various properties and set the value from the Xml Node.

public static List<T> FillCollectionObject<T>(XmlNodeList nodeList) where T : new()
//Construct an object for the List.
List<T> listObject = new List<T>();

//Iterate through the xmlnodelist.
foreach (XmlNode rowXmlNode in nodeList)
//Create object for the type T
T tObject = Activator.CreateInstance<T>();

//Get the properties using reflection for Type T.
PropertyInfo[] properties = typeof(T).GetProperties();

//Iterate through the properties.
foreach (PropertyInfo property in properties)
//Checking whether the property has write access (i.e) writeonly.
if (property.CanWrite)
if (rowXmlNode.SelectSingleNode("./" + property.Name) != null)
//Convert to desire datatype using ConvertToObject.
object objConverted = ConvertToObject(property.PropertyType, rowXmlNode.SelectSingleNode("./" + property.Name).InnerText.Trim());

//Set the property value.
property.SetValue(tObject, objConverted, null);

//Add to the list of objects.
catch (Exception ex)
throw ex;

return listObject;

//Method to convert DataTable to XML
public static string ConvertDataTableToXML(DataTable xmlDT)
MemoryStream stream = null;
XmlTextWriter writer = null;
stream = new MemoryStream();
// Load the XmlTextReader from the stream
writer = new XmlTextWriter(stream, Encoding.Unicode);

// Write to the file with the WriteXml method.
xmlDT.WriteXml(writer, XmlWriteMode.IgnoreSchema);
int count = (int)stream.Length;
byte[] arr = new byte[count];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(arr, 0, count);
UnicodeEncoding utf = new UnicodeEncoding();
return utf.GetString(arr).Trim();
catch (Exception excp)
throw excp;
if (writer != null) writer.Close();

Comments or Responses

Posted by: Hi_anilanand on: 3/12/2010 Level:Starter | Status: [Member]
Hi ,

I see your code. But in this code , there is a one method ConvertToObject . but u not mention the definition if this method. please peovide the definition of this method. otherwise this post is useless.

Anil Anand

Login to post response