Skip to content

Instantly share code, notes, and snippets.

@Gateswong
Last active April 21, 2016 19:22
Show Gist options
  • Select an option

  • Save Gateswong/0395ac30b9c900b8f969701307314acc to your computer and use it in GitHub Desktop.

Select an option

Save Gateswong/0395ac30b9c900b8f969701307314acc to your computer and use it in GitHub Desktop.
This is a code segment can be used in LinqPad 5
ID: 1
CreateDate: 4/21/2016 14:18:54
Name: Hello
ID: 2
Name: Good Bye
CreateDate: 1/1/0001 00:00:00
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public DateTime CreateDate { get; set; }
public XDocument XML { get; set;}
}
void Main()
{
Student s = new Student()
{
ID = 1,
Name = "Hello",
CreateDate = DateTime.Now,
XML = new XDocument(),
}, s2 = new Student()
{
ID = 2,
Name = "Good Bye",
CreateDate = DateTime.MinValue,
XML = new XDocument(),
};
// foreach (PropertyDescriptor p in TypeDescriptor.GetProperties(typeof(Student)))
// {
// if (p.PropertyType.IsValueType || p.PropertyType == typeof(string))
// {
// p.Name.Dump();
// p.GetValue(s).Dump();
// }
// }
PrintContents(s, a => a.ID, a => a.CreateDate, a => a.Name);
PrintContents(s2, a => a.ID, a2 => a2.Name, a2 => a2.CreateDate);
}
public void PrintContents<T>(T obj, params Expression<Func<T, object>>[] predicators)
{
foreach (Expression<Func<T, object>> p in predicators)
{
Type type = typeof(T);
if (p.Body is MemberExpression)
{
MemberExpression e = p.Body as MemberExpression;
$"{e.Member.Name}: {type.GetProperty(e.Member.Name).GetValue(obj)}".Dump();
}
else if (p.Body is UnaryExpression)
{
UnaryExpression e = p.Body as UnaryExpression;
string name = (e.Operand as MemberExpression).Member.Name;
$"{name}: {type.GetProperty(name).GetValue(obj)}".Dump();
}
else
{
p.Body.Dump();
}
}
}
// Define other methods and classes here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment