Reputation: 63
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.
Upvotes: 6
Views: 25087
Reputation: 2983
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)
Upvotes: 0
Reputation: 3785
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.
Upvotes: 11
Reputation: 24395
Is this what you mean?
return commandList
.Where(t => t.Name == "someName")
.Select(t => t.Callback)
.ToArray();
Upvotes: 2