C# Lambda-Select with conditions

依然范特西╮ 提交于 2020-12-08 07:02:53

问题


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:


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.




回答2:


Is this what you mean?

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



回答3:


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)


来源:https://stackoverflow.com/questions/36290665/c-sharp-lambda-select-with-conditions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!