Guys,
A correction, the syntax { a,b,c => a*b*c } in X# IS a proper lambda expression, we have just used the curly braces {} to make the syntax more close to the one we know from codeblocks, but the above is not a codeblock. For an expression to be a codeblock, the || characters are also required (and the => operator should not be included), as in { |a,b,c| a*b*c }, as we know it from Clipper etc.
Kees, to explain the code a bit more, what it essentially does is this:
Code: Select all
FUNCTION GetCheckedRadio(oGroupBox AS GroupBox) AS RadioButton
FOREACH oControl AS Control IN oGroupBox:Controls
IF oControl IS RadioButton VAR oRadioButton // if control is a radiobutton, then it is assigned to the new local variable "oRadioButton"
IF oRadioButton:Checked
RETURN oRadioButton
END IF
END IF
NEXT
RETURN NULL
which is pretty standard and self self explainable code, except maybe for the IS <type> VAR <oNewVar> code pattern which is new in X#/.Net, but could also had be written in two separate lines without it also.
In the above code, oGroupBox:Controls represents a collection (of controls), and the code you found cuts the code down by using the method OfType() which is available for collections, and returns a new collection, which includes only the original items of the type you specify, so another way to write this is:
Code: Select all
FUNCTION GetCheckedRadio(oGroupBox AS GroupBox) AS RadioButton
FOREACH oRadioButton AS RadioButton IN oGroupBox:Controls:OfType<RadioButton>()
IF oRadioButton:Checked
RETURN oRadioButton
END IF
NEXT
RETURN NULL
Finally, in order to further cut down the above code, the sample uses the FirstOrDefault() method that can be applied to collections and returns the first item that satisfies a condition (that it is "Checked" in our case), or returns NULL if no item satisfies it:
Code: Select all
FUNCTION GetCheckedRadio(oGroupBox AS GroupBox) AS RadioButton
RETURN oGroupBox:Controls:OfType<RadioButton>():FirstOrDefault( {oRadioButton AS RadioButton => oRadioButton:Checked} )
So the code you found does what you want in a very neat and powerful way in just a single line of code, which is great for demonstrating the power of .Net and also demonstrates the poster's knowledge and one might even say it's plain showoff
But it's probably also making it very difficult for others to read and understand the code, without spending much time on it..For this reason, I usually personally prefer the longer versions of the code which are easier to read.