Sometimes ago, I was working in project and there are following scenario:
First Scenario: In this situation, I have to copy values from one class to another class. I am providing the following code snippet which is useful for this:
#region Deep Copy
/// <summary>
/// This method is used to copy values from one class to another class
/// </summary>
/// <param name="dst">Destination Class</param>
/// <param name="src">Source Class</param>
public static void DeepCopyShallow(this Object dst, object src)
{
var srcT = src.GetType();
var dstT = dst.GetType();
foreach (var f in srcT.GetFields())
{
var dstF = dstT.GetField(f.Name);
if (dstF == null)
continue;
dstF.SetValue(dst, f.GetValue(src));
}
foreach (var f in srcT.GetProperties())
{
var dstF = dstT.GetProperty(f.Name);
if (dstF == null)
continue;
dstF.SetValue(dst, f.GetValue(src, null), null);
}
}
#endregionSecond Scenario: In this situation, I have to convert list object to datatable object. I am providing the following code snippet which is useful for this:
#region ConvertToDataTable
/// <summary>
/// This method is used to convert list to datatable
/// </summary>
/// <typeparam name="T">Class Type</typeparam>
/// <param name="items">Class Object</param>
/// <returns></returns>
public static DataTable ToDataTable<T>(List<T> items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
//Get all the properties
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{
//Setting column names as Property names
dataTable.Columns.Add(prop.Name);
}
foreach (T item in items)
{
var values = new object[Props.Length];
for (int i = 0; i < Props.Length; i++)
{
//inserting property values to datatable rows
values[i] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
//put a breakpoint here and check datatable
return dataTable;
}
#endregionNote: The above methods are static and it can only be defined in the static class. Just provide the objects in this static method.
That’s it. Happy Coding!!
