Method without parameters in C # and another method?

All I'm trying to do is check if all the items in list B are in list A

if (listA.All(element => listB.Contains(element)) { return; } 

Someone came up with a different solution, saying it would work, and it worked!

  if (listA.All(listB.Contains)) return; 

Now (I know this works)

  • Why doesn't the compiler require () next to it in the second method?
  • If in the future, let's say I want this to be case insensitive, how would I do this with the second method?

Thanks in advance.

+4
source share
1 answer

The All method asks for the predicate as a parameter: Func<T, bool> where T is the same type, these are elements in List<T> . This code works because it provides just such a method. The All method will return a value indicating whether the result of calling the predicate provided for each element in the list is true . The parameter refers to the Contains method, which corresponds to the required Func<T, bool> , taking a single parameter T and returning bool .

Consider these two lines of code:

 Func<string, bool> predicate1 = s => s.Length > 5; Func<string, bool> predicate2 = listB.Contains; 

Both of these lines work because the expressions to the right of the assignment operators are evaluated by methods that take one string parameter and return a bool . You can pass predicate1 or predicate2 to the All method. This is the same as the code you provided, except that the predicate is passed directly, instead of being stored in the first variable and the variable passed to.

The Contains method is not really called a parameter. It is called only inside the All method.

If you want to do case-insensitive searches and use the same syntax as above, you need a method that would perform case-insensitive cases. You can always use a custom anonymous method:

 listA.All(x => listB.Any( z => string.Equals(x, z, StringComparison.OrdinalIgnoreCase))); 
+13
source

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


All Articles