1

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);
    }
}

2 Answers 2

8

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this is very helpful and detailed. I'll read about lambda expressions.
1

ob means an item in excludeItems

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.