6

I created a Command-class which has two important members.

public class Command
{
    public string Name { get; set; }
    public CommandExecutedCallback Callback { get; set; }
    public delegate void CommandExecutedCallback(Command command);
}

I save multiple objects of this class in a List<Command>.

Another class CommandProcessor has a member function GetCallbacks(string name).

I want to use a lambda expression to get an array of CommandExecutedCallback-delegates with the condition that the name matches.

I can get all Callbacks with: return commandList.Select(t => t.Callback).ToArray().

How can i insert the condition to get only commands with the specified name?

Thank you in advance.

1
  • 1
    Select is for a projection. Use Where for filtering. Commented Mar 29, 2016 at 17:08

3 Answers 3

11

You need to a add a Where condition:

return commandList.Where(t => t.Name == name).Select(t => t.Callback);

You should also avoid calling ToArray unless you really need to. Unless you're specifically passing this data to some other method that requires an array, copying all of the data with ToArray is probably an unnecessary (and rather expensive) operation.

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

1 Comment

This is exactly what i was looking for. Thank you so much.
2

Is this what you mean?

return commandList
    .Where(t => t.Name == "someName")
    .Select(t => t.Callback)
    .ToArray();

1 Comment

Also, this is what i was looking for. Thank you too :)
0

You need to use the WHERE not the SELECT. With Select you tell what you wnat from the list, and with WHERE you filter the list to show.

return commandList.Where(t => t.Name == "VALUE").Select(t => t.Callback)

2 Comments

You dropped the Select, which is still necessary.
I changed it, but I think its more important if he understand the difference between both of them.

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.