Pavel Tsybulivskyi Pavel Tsybulivskyi - 3 months ago 17
C# Question

Extracting lambda expression from LINQ

I have next chunk of code

var query = wordCollection.Select((word) => { return word.ToUpper(); })
.Where((word) =>
{
return String.IsNullOrEmpty(word);
})
.ToList();


Suppose I want to refactor this code and extract the lambda expression from Where clause. In Visual Studio I just select this lambda and do Refactor -> Extract Method. By doing so I have my LINQ modified to

var query = wordCollection.Select((word) => { return word.ToUpper(); })
.Where(NewMethod1())
.ToList();


and a NewMethod1() is declared as

private static Func<string, bool> NewMethod1()
{
return (word) =>
{
return String.IsNullOrEmpty(word);
};
}


The question is why this new method does NOT have any input parameters, as delegate Func states that NewMethod1() should have a string input parameter?

Answer

To get the expected result, mark just this part String.IsNullOrEmpty(word) and Extract the method:

private bool NewMethod(string word)
{
    return String.IsNullOrEmpty(word);
}  

What you originally got is because the extract created a method that returns a delegate. Not a method that matches the delegate. It is a method that returns another method. The latter accepts a string parameter word and returns a bool result.

Sure doing the above changes your code to:

.Where((word) => NewMethod(word))

But you can safely change that to:

.Where(NewMethod)

Side Note:

No need to use the return keyword in your Linq Queries or any one-line lambda, you can refactor you query to be like this:

var query = wordCollection.Select(word => word.ToUpper())
                          .Where(word => string.IsNullOrEmpty(word))
                          .ToList();
Comments