Last active
July 9, 2016 10:40
-
-
Save svdamani/0f61f05ee941bd177ce0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Data; | |
using System.Runtime.CompilerServices; | |
public static class ObjectExtensions { | |
public static void Dump(this Object o) { | |
Console.WriteLine("{0,-30} {1}", "Name", "Value"); | |
Console.WriteLine("-----------------------------------------------------------------"); | |
foreach (var prop in o.GetType().GetProperties()) | |
try { | |
Console.WriteLine("{0,-30} {1}", prop.Name, prop.GetValue(o, null)); | |
} | |
catch { } | |
Console.WriteLine(); | |
} | |
public static DataTable ToTable(this object o, string tableName = null) { | |
if (o == null || o is DataTable) | |
return o as DataTable; | |
var type = o.GetType(); | |
var table = new DataTable(tableName ?? type.Name); | |
if (type.IsValueType || type == typeof(string)) { | |
table.Columns.Add("Value", Nullable.GetUnderlyingType(type) ?? type); | |
table.Rows.Add(o); | |
} | |
else { | |
var props = type.GetProperties(); | |
var values = new object[props.Length]; | |
for (var i = 0; i < props.Length; ++i) { | |
table.Columns.Add(props[i].Name, Nullable.GetUnderlyingType(props[i].PropertyType) ?? props[i].PropertyType); | |
values[i] = props[i].GetValue(o) ?? DBNull.Value; | |
} | |
table.Rows.Add(values); | |
} | |
return table; | |
} | |
public static DataTable ToTable<T>(this IEnumerable<T> items, string tableName = null) { | |
var type = typeof(T); | |
var table = new DataTable(tableName ?? type.Name); | |
if (type.IsValueType || type == typeof(string)) { | |
table.Columns.Add("Value", Nullable.GetUnderlyingType(type) ?? type); | |
foreach (var item in items) | |
table.Rows.Add(item); | |
} | |
else { | |
var props = type.GetProperties(); | |
foreach (var prop in props) | |
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType); | |
foreach (var item in items) { | |
var values = new object[props.Length]; | |
for (var i = 0; i < props.Length; i++) | |
values[i] = props[i].GetValue(item) ?? DBNull.Value; | |
table.Rows.Add(values); | |
} | |
} | |
return table; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment