Someone pointed out in the comments that the GetPropertySymbol function I wrote in a previous post did not handle nested member expressions. For example this.GetPropertySymbol( o => o.Person.Name ) would only return "Name", not "Person.Name". At first I just told him how to do it. Then I decided to do it because I could use the opportunity to demonstrate some cool C# 3.0-style functional programming.
I wrote the algorithm in functional style to challenge you to start thinking this way. The Iterate method takes a function and an initial value and then returns that initial value and then the result of passing the value to the function, the result of which is then passed back to the function for the next value and so on and so on. I stole this function from Haskell. It works this way...
Iterate( x => x + 10, 0)
...returns the following stream...
The initial member expression is passed to iterate and every time the next member expression is required the function takes the member expression and attempts to convert its inner expression to a member expression using the "as" operator. If this conversion fails the "as" operator returns null. Then the resulting data is piped through TakeWhile which ensures that the stream stops when the first null value is passed to it. Finally I aggregate the stream of member expressions into a string by concatenating the member names, separated by a period.
Pretty neat huh?
- ► 2009 (20)
- ► 2008 (18)