Conversion Classes


Convert from Model to Dataset


public static DataSet ToDataSet(this IList list)
{
Type elementType = typeof(T);
DataSet ds = new DataSet();
DataTable t = new DataTable();
ds.Tables.Add(t);

//add a column to table for each public property on T
foreach (var propInfo in elementType.GetProperties())
{
Type ColType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;

t.Columns.Add(propInfo.Name, ColType);
}

//go through each property on T and add each value to the table
foreach (T item in list)
{
DataRow row = t.NewRow();

foreach (var propInfo in elementType.GetProperties())
{
row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
}

t.Rows.Add(row);
}

return ds;
}

Convert from Array to Dataset



public static DataSet ToDataSetFromArrayOfObject(this object[] arrCollection)
{
DataSet ds = new DataSet();
try
{
XmlSerializer serializer = new XmlSerializer(arrCollection.GetType);
System.IO.StringWriter sw = new System.IO.StringWriter();
serializer.Serialize(sw, dsCollection);
System.IO.StringReader reader = new System.IO.StringReader(sw.ToString());
ds.ReadXml(reader);
}
catch (Exception ex)
{
throw (new Exception("Error While Converting Array of Object to Dataset."));
}
return ds;
}

Comments

Popular posts from this blog

Linq Exclude from separate list

Sorting Ascending and Descending

Linq Query Syntax vs Method Syntax