Hello!
Sorry to bother with this question, maybe it´s a very simple one, but after spending some time I can´t fully understand it. I don´t pretend to get an explanation, but a definition that guide me in the right direction, so I can take it from there.
So this is the line I’m struggling with:
bool results = myListA.All(i => myListB.Contains(i));
Is this a lambda expression? Or just a complex bool construction?
I think what this is doing is to assign a value to a boolean based on going through all the items on list A one by one(that must be “i”) and checking if every one of those items is already in list B. Am I right?
But other than a lambda expression (which I don´t know at all), I have no idea what the => operator does (already google it, but couldn´t find a lambda construction build as this is, which makes me doubt this is a lambda)
Thanks for your kind help!
This is using “linq”. Specifically the “Enumerable.All” method:
It evaluates the passed in lambda (the i => myListB.Contains(i) portion) on every element as variable i. And it returns true if every one evaluated true.
That lambda which uses the i => … is short hand… it’s like saying:
bool (i)
{
return myListB.Contains(i);
}
Just with shorter syntax.
1 Like
Yes, it is a lambda expression, albeit one whose syntax is extremely pared down, making it a little harder to follow if you’re not familiar with them.
If it helps you to follow the syntax, these are all functionally equivalent:
bool results = myListA.All(i => myListB.Contains(i));
//equals....
bool results = myListA.All(
(i) => {
return myListB.Contains(i);
});
//equals....
bool results = myListA.All(ContainmentCheck);
private bool ContainmentCheck(object i) {
return myListB.Contains(i);
}
If you leave off the brackets from a => statement, then the compiler also assumes a “return” statement, which is probably what threw you off.
1 Like
Thank you very much for your answers, lordofduct and StarManta! You really helped me a lot to understand this!