简体   繁体   English

如何从C#中的Lambda表达式中删除列表项?

[英]How to remove a list item from a lambda expression in c#?

If I have this 如果我有这个

private static List<Action> actions = new List<Action>();

private static void Main()
{
    for (var i = 0; i < 10; i += 1)
    {
        Action action = async () => {
            // want to remove this specific lambda item from the "actions" variable. 
            // is there something like this:
            /*
                Action this_action = this;
                actions.Remove(this_action);
            */
        };

        actions.Add(action);
    }

    Parallel.Invoke(actions.ToArray());

    Console.Write("\nPress any key to exit...");
    Console.ReadKey();
}

How can I properly remove it from the list. 如何从列表中正确删除它。 I would need some kind of self reference? 我需要某种自我参考吗?

Note: 注意:
It's the action that was just run should be the one to be removed. 刚执行的操作应该被删除。 The actions may not finish in the same order as how they are added to the list, but the one that ran should be the one removed. 这些动作的完成顺序可能与将其添加到列表的顺序不同,但是执行的动作应该是删除的动作。 And I don't want to remove them all at the same time, only as they finish. 而且我不想同时删除它们,只能等它们完成后再删除。

Thanks 谢谢

You can just use the reference to action to remove the action's instance. 您可以仅使用对action的引用来删除操作的实例。 Closure will make sure that the reference is pointing to the correct object. 关闭将确保引用指向正确的对象。

for (var i = 0; i < 10; i += 1)
{
    Action action = null;
    action = () => {
        actions.Remove(action);
    };

    actions.Add(action);
}

Parallel.Invoke(actions.ToArray());

See Fiddle for a working example. 有关有效的示例,请参见Fiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 C# 的列表中删除项目? - How to remove item from list in C#? 如何从 C# 中的 lambda 表达式列表构造 IEnumerable? - How to construct IEnumerable from a list of lambda expression in c#? c#从列表中选择lambda表达式 - c# selecting from list with lambda expression 如何使用lambda表达式过滤C#中的列表? - How to filter a list in C# with lambda expression? 如何通过C#中的lambda表达式将元组的一个项匹配到另一个列表来过滤元组列表? - How to filter a list of tuples based on matching one item of the tuple to another list through lambda expression in C#? c# lambda 表达式根据不同列表中的给定条件从列表中删除项目 - c# lambda expression to remove items from a list based on given conditions in a different list 引用列表项构造C#Lambda表达式 - Construct C# Lambda Expression With Reference To List Item C#如何使用lambda表达式对字符串列表进行排序,具体取决于每个项目中的字符子集 - C# How to sort a List of Strings using lambda expression depending upon a subset of characters inside each item 如何在 C# 的字符串列表中添加 Lambda 表达式 - How do I prepend every item in a list of strings in C# with a Lambda Expression 如何从Windows Phone 8 App C#的列表中删除项目 - how to remove a item from list in Windows Phone 8 App C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM