I have a requirement to modify a method so that it has an extra parameter that will take a lambda expression that will be used on an internal object to return the value of the given property. Forgive my probable incorrect use of terminology as this is my first foray into LINQ expressions!
I have tried searching for an answer, but as I mentioned, my terminology seems to be off and the examples I can find are far too complex or deal with expressions for collection functions such as .Where()
, which I am familiar with.
What I have so far (cut down version):
class MyClass { private MyObject _myObject = new MyObject() { Name = "Test", Code = "T" }; private string MyMethod(int testParameter, ??? selector) { //return _myObject.Name; //return _myObject.Code; return ???; } }
I would like to call it something like this:
string result = _myClassInstance.MyMethod(1, (x => x.Name));
or:
string result = _myClassInstance.MyMethod(1, (x => x.Code));
Obviously the parts which I am missing is the selector
parameter in MyMethod
, how to apply it to the local variable and how to pass the required property into the method when I am invoking it.
Any help would be appreciated, also extra bonus points for a VB.NET solutions as well as unfortunately the final implementation needs to be in our lone VB project!
private string MyMethod(int testParameter, Func<MyObject, string> selector) { return selector(_myObject); }
When using Func
delegates, the last parameter is the return type and the first N-1 are the argument types. In this case, there is a single MyObject
argument to selector
and it returns a string
.
You can invoke it like:
string name = _myClassInstance.MyMethod(1, x => x.Name); string result = _myClassInstance.MyMethod(1, x => x.Code);
Since the return type of MyMethod
matches the return type of your selector
delegate, you could make it generic:
private T MyMethod<T>(int testParameter, Func<MyObject, T> selector) { MyObject obj = // return selector(obj); }
I don't know VB.Net but it looks like it would be:
Public Function MyMethod(testParameter as Integer, selector as Func(Of MyObject, String)) Return selector(_myObject) End Function
and the generic version would be:
Public Function MyMethod(Of T)(testParameter as Integer, selector Func(Of MyObject, T)) Return selector(_myObject) End Function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With