Reputation: 4377
There is some code, but the thing is very simple. I want to pass a function as a parameter, but the function is so short that it could've been created by lambda.
class Hidden
{
public List<string> GetData()
{
return new List<string>();
}
}
class Main
{
Dictionary<int, Hidden> dir = new Dictionary<int, Hidden>();
public Main()
{
Friend f = new Friend(MethodToBeReplacedByLambda);
}
public List<string> MethodToBeReplacedByLambda(int id)
{
return dir[id].GetData();
}
}
class Friend
{
public Friend(Func<int, List<string>> GetData)
{
List<string> result = GetData(4);
}
}
I want to delete this method
public List<string> MethodToBeReplacedByLambda(int id)
{
return dir[id].GetData();
}
And be able to pass this as a parameter by lambda. Any ideas? :D
UPDATE: I've tried:
Friend f = new Friend((int, List<string>) => dir[id].GetData());
Upvotes: 0
Views: 136
Reputation: 14153
Simply create a lambda that uses the int value from the function:
Friend f = new Friend(id => dir[id].GetData())
Only the parameter names (that you use) need to be passed to the lambda, and not the return value of GetData
. If you have multiple parameters, wrap them in parenthesis.
Upvotes: 2