Reputation: 105
What does ob means in following code - is this same as item?
foreach (var item in allItems)
{
if (excludeItems.Exists(ob => ob.Equals(item)))
{
Console.WriteLine("Item {0} excluded",item);
}
}
Upvotes: 1
Views: 167
Reputation: 1500504
ob
is the parameter to the lambda expression. So if you're familiar with anonymous methods, it's like:
foreach (var item in allItems)
{
if (excludeItems.Exists(delegate (string ob) { return ob.Equals(item); })
{
Console.WriteLine("Item {0} excluded",item);
}
}
That's assuming the type of ob
should be string
- it may well not be. That will depend of excludeItems
, due to generic type inference.
Lambda expressions can be more explicit, so this could be written as:
if (excludeItems.Exists((string ob) => { return ob.Equals(item); })
or
if (excludeItems.Exists((string ob) => ob.Equals(item))
Basically there are several little shortcuts in lambda expressions for the common case of a single parameter whose type can be inferred, and a return value from a single expression.
Now in this particular case, the delegate created from the lambda expression will be called once for each element in excludeItems
(in each iteration of the foreach
loop) and ob
will have the value of that element, until it finds a value equal to item
(or runs out of elements).
Upvotes: 8