Geeks With Blogs

News Google

Nick Harrison Blog<Nick>.Next()

I have recently started playing around with linq syntax. It can produce some very beautiful syntax. Of course, it can probably also produce equally ugly ones.


I recently played around and built this one lines for retrieving the values for all of the readable properties in a object.



var values = (from prop in value.GetType().GetProperties()

where prop.CanRead

select new { Name = prop.Name, Value = prop.GetValue(value, null) });



This allows us a single statement to retrieve name / value list for all of the properties in an object.

This allows us to skip having to write the foreach loop and the conditional on the CanRead property. Additional conditionals could be replaced by adding more elements to the where clause.

I believe that these format is much easier to follow and understand. It also puts the focus of the code back to where it belongs, which usually is not reflection or identifying which elements in a collection to work with, but the actual work being done to the identifed elements from the collection.


What are your thoughts?

Posted on Tuesday, June 29, 2010 12:55 PM LINQ | Back to top

Comments on this post: Reflection Linqiness

# re: Reflection Linqiness
Requesting Gravatar...
My favorite collection of reflection helpers is what FubuMVC uses. The heavy lifting is in ReflectionHelper.cs.
Left by Ryan on Jun 29, 2010 4:38 PM

comments powered by Disqus

Copyright © Nick Harrison | Powered by: