Compiler error when replacing Lambda expression with method group

I like the Linq syntax and its power, but sometimes I just can't understand why everything works, when they work.

Like now. I have the following code:

Regex regex = new Regex( ... ); int result1 = stringList.Count(regex.IsMatch); IEnumerable<string> result2 = stringList.Where (x => regex.IsMatch (x)); 

As you can see in the first request, I can use a shorter group of methods 'regex.IsMatch', but in the second request I need to write 'x => regex.IsMatch (x)'.

Like a graph and where both take the same type argument

 Func<string, bool> 

I do not understand why I get a compiler error when I do this:

 IEnumerable<string> result2 = stringList.Where (regex.IsMatch); 
+4
source share
1 answer

In essence, this is a problem with overload resolution.

Count has only one overload, which takes two arguments (extended argument + predicate), but Where has two (one where the predicate considers the index of the element, and one that does not). To complicate matters, Regex.IsMatch has several overloads. Now it turns out that the compiler is right to complain about the ambiguity, since two of these IsMatch overloads IsMatch really applicable (each of them is compatible with the other Where overload):

 // Where overload without item-index Regex.IsMatch(string) is compatible with Where<string>(string, Func<string, bool>) // Where overload with item-index Regex.IsMatch(string, int) is compatible with Where<string>(string, Func<string, int, bool>) 

... but there may be other related cases related to groups of methods (when return type analysis is required) where the compiler may complain about ambiguity, even if there is no ambiguity for a person .

+5
source

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


All Articles