C#Lambda-Select有条件

问题描述:

我创建了一个具有两个重要成员的Command类.

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

我将此类的多个对象保存在List<Command>中.

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

另一个类CommandProcessor具有成员函数GetCallbacks(string name).

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

我想使用lambda表达式获取名称匹配的CommandExecutedCallback -delegates数组.

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

我可以使用return commandList.Select(t => t.Callback).ToArray()来获取所有回调.

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?

谢谢.

您需要添加Where条件:

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

除非确实需要,否则还应避免致电ToArray.除非您专门将此数据传递给其他需要数组的方法,否则使用ToArray复制所有数据可能是不必要的(而且相当昂贵)操作.

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.