Why can I leave the parameter from the LINQ condition?

I read this answer on how to search a string for any of the strings contained in an array. The solution is beautifully concise:

if(stringArray.Any(stringToCheck.Contains))

My question is that the term Contains()does not require an explicit parameter? I would write above:

if(stringArray.Any(s => stringToCheck.Contains(s)))

What are the rules for using this shortened version?

+4
source share
4 answers

Anyneed a function ( Func), which (and I assume it stringArrayis just a string)

  • accepts input char
  • returns a bool.

( ). . , , , .

, Contains char a bool. ( ).

, , :

public static bool Contains2 (this string input, char c)
{
    //....
}

stringArray.Any(stringToCheck.Contains2)

. , Contains2 (). , .

, char (s =>) bool ( Contains(s)).

+4

Any Func<TSource, bool>, Contains , , , stringToCheck.Contains(s)

+1

n . , , . , stringToCheck.Contains , Any.

0

:

public static bool Any<TSource>(
    this IEnumerable<TSource> source,
    Func<TSource, bool> predicate
)

- stringToCheck.Contains.

-1

Source: https://habr.com/ru/post/1545097/


All Articles