string.Contains as a predicate not a function call?

  • A+
Category:Languages

I found this sample of code on SO (can't remember from where :/) that allowed me to check for line code arguments when launching my application :

if (e.Args.Length == 0 || e.Args.Any("-show".Contains)) {   //show interface... } 

I just can't seem to understand how the "-show".Contains works. And if there's any difference with a (classic) x => x.Contains('"-show") (except for the evident typing gain).

Works like a charm but I'd like to understand why, I feel like something big is hapening.


This:

.Any("-show".Contains) 

is basically shorthand for this:

.Any(s => "-show".Contains(s)) 

The Any method takes a delegate as a parameter and you can create that delegate in a number of ways. The first snippet uses a method group while the second uses a Lambda.

It's not really accurate to say that the first is shorthand for the second because method groups predate Lambdas, but if you think in terms of Lambdas when calling LINQ methods like Any then it is effectively the case.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: