简体   繁体   中英

Why when using String.contains in a Linq expression, are parentheses not required?

I was reading a solution on a coding exercise site and it was for determining if a sentence is a pangram and I came across this solution:

"abcdefghijklmnopqrstuvwxyz".All(input.ToLower().Contains);

For whatever reason, Contains() is not needed and this compiles just fine. I'm fairly inexperienced with the intricacies of LINQ, so I was wondering if anyone can answer or point me to an answer on this.

The reason Contains does not need the parentheses is because you are passing the function as the parameter to the All function and not the result of the function. If you look at the definition of All you see:

public static bool All<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, 
                                 Func<TSource,bool> predicate);

'All' is expecting a Func<TSource,bool> . In this case TSource is char so All is expecting the given parameter to be a reference to a function that receives a character and returns a boolean - which is exactly what Contains does.

You could also write it the following way and it will result in the same output (but might look a bit more messy): ( For the difference see @pinkfloydx33's comment below )

"abcdefghijklmnopqrstuvwxyz".All(c => input.ToLower().Contains(c));

Firstly, you should look at the input type.

Here, All method takes input: Func<TSource, bool> predicate

All method is: public static bool All<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)

And Contains method is: public static bool Contains<TSource>(this IEnumerable<TSource> source, TSource value)

Now, we see that the Contains method is a delegate that is same as All method input predicate. So, we pass the Contains method as a delegate, not the output of Contains method through the All method.

So, we should write:

"abcdefghijklmnopqrstuvwxyz".All(input.ToLower().Contains);

If we write : "abcdefghijklmnopqrstuvwxyz".All(input.ToLower().Contains()); then it return bool as All method input, that must not work.

But if we want to use parentheses then you may use it in this way:

"abcdefghijklmnopqrstuvwxyz".Contains(input)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM