C#,RemoveAll 仅删除特定索引时出现问题

C#, Trouble with RemoveAll removing only specific indexes

我的代码和设置谓词语句时遇到一些问题。 C# 不是我学习编码的主要语言,lambda 语句也不是我完全熟悉的语言。

这是我需要的示例 运行,代码按预期工作,但人们认为最好使用 RemoveAll 方法而不是 foreach->while->if我有一个循环。

为了后代,下面是 "working" 函数。当前用作包装函数。

private void UnassignHelper(ThingDbFactory thingFactory,     
IEnumerable<Thing> assignedThings, string groupName)
{
    foreach(var thing in assignedThings)
        while(thing.ThingGroups.Contains(groupName))
        {
            if(thing.ThingGroups.Remove(groupName))
            {
                thingFactory.Save(thing);
            }
        }
}

这个代码金字塔虽然丑陋,但它完全符合预期。有人问我改用 RemoveAll() ,但问题是我目前测试的方法不起作用。

item.ItemGroups.RemoveAll(i => item.ItemGroups.Contains(itemGroupName));

已经过测试,该方法已经删除了我所有的 ItemGroup 分配,而不仅仅是我需要删除的 ItemGroup 分配。

item.ItemGroups.RemoveAll(i => item.ItemGroups == itemGroupName);

无效,因为我无法比较 System.Collections.Generic.List 和字符串。

item.ItemGroups.RemoveAll(i => item.ItemGroups.Equals(itemGroupName));

是有效代码,但在 运行 宁代码时它不做任何事情。

对于进一步的文档,我试图比较的不是键,而是值itemGroupName,这里是与问题相关的项目的结构。

{
    "_id" : 1,
    "Name" : "Banana",
    "ItemGroups" : [
        "Not the group to remove",
        "The duplicated group to remove",
        "The duplicated group to remove",
        "The duplicated group to remove"
    ],
}

其中,在通过 Visual Studio 进行调试时,实际项目将如此反映(使用模拟结构在其上放置手表时的外观):

item
----ItemGroups
--------[0]["not the group to remove"]
--------[1]["the duplicate group to remove"]
--------[2]["the duplicate group to remove"]
--------[3]["the duplicate group to remove"]

任何关于如何在不使用 foreach->while->if 循环的情况下更好地构建代码的建议将不胜感激。

RemoveAll 中的谓词应确定是否应删除特定项目。这就是为什么您将项目作为 lambda 中的输入参数 i

这应该可以完成您正在寻找的工作:

item.ItemGroups.RemoveAll(i => i == groupName);

i 是输入,在本例中是 ItemGroups 列表中的每一项。如果应该删除该项目,lambda 应该 return 为真。 i == groupName 检查输入是否与您要查找的组名匹配。