Extract all object properties with Linq

Linq is fantastic! I wanted to exctract all the properties of an object into a string, and this is what I came up with:

var t = new Test{t3="Hello", t4 = DateTime.Now};

var s =
    typeof(Test)
    .GetProperties()
    .Select(p => new {p.Name, Value = p.GetValue(t, null)})
    .Select(p => string.Format("{0}({1})",p.Name,(p.Value == null ? "NULL" : p.Value.ToString())))
    .Aggregate((s1,s2) => s1 + " " + s2);

The first Select extracts all object values, number two formats each name/value (taking care of nulls), and the Aggregate finally joins it all…

Advertisements
Posted in C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s