XN16 XN16 - 1 year ago 170
Vb.net Question

Lambda property value selector as parameter

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

, 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));


string result = _myClassInstance.MyMethod(1, (x => x.Code));

Obviously the parts which I am missing is the
parameter in
, 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!

Lee Lee
Answer Source
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);

EDIT: 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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download