【问题标题】:List<T> RemoveAll() isn't removing itemsList<T> RemoveAll() 没有删除项目
【发布时间】:2015-10-19 09:59:58
【问题描述】:

我有一个看起来像这样的对象:

{
  "Text" : "Another lovely alert",
  "Category" : 2,
  "UserAlerts" : [{ "UserId" : 2 }]
}

这被传递到 Web API 并正确绑定到:

[Key, Column(Order = 0)]
public long UserId { get; set; }

[Key, Column(Order = 1)]
public Guid AlertId { get; set; }

public virtual User User { get; set; }

public virtual Alert Alert { get; set; }

然后我运行以下命令,期望 ID 为 2 的 UserAlert 被删除,但对象没有改变。

alert.UserAlerts.ToList().RemoveAll(x => userIds.Contains(x.UserId));

alert.UserAlerts.ToList().RemoveAll(x => x.UserId == 2);

第二个查询更简单,但这也无济于事。我不知道我哪里出错了。

【问题讨论】:

    标签: c# linq list


    【解决方案1】:

    这是因为通过使用ToList,您正在创建新的 List 对象,然后从中删除项目,而不是从原始 IEnumerable 中删除。

    试试这个:

    alert.UserAlerts = alert.UserAlerts.Where(x => x.UserId != 2);
    

    你不能在IEnumerable 上运行RemoveAll,所以我认为在这里使用Linq 是个好主意。您将收集到没有UserId=2 的项目,这相当于删除所有具有UserId=2 的项目。您需要从RemoveAll 反转您的查询,它在任何情况下都可以工作。

    【讨论】:

      【解决方案2】:

      这当然应该删除元素,但我看不出你怎么会注意到它是否有?

      首先,您使用ToList() 创建列表,然后调用RemoveAll() 从该列表中删除一些元素,但是由于您没有将该列表存储在任何地方,您只会得到删除的项目数返回。

      【讨论】:

        【解决方案3】:

        您必须在alert.UserAlerts 上调用RemoveAll,因为ToList 会创建一个新集合。
        如果您删除该集合的所有项目,它不会更改 UserAlerts

        alert.UserAlerts.RemoveAll(x => userIds.Contains(x.UserId));
        

        更新:
        如果UserAlerts 不是List,请使用Where 扩展方法(正如wudzik 在他的回答中所说):

        alert.UserAlerts = alert.UserAlerts.Where(x => !userIds.Contains(x.UserId));
        

        【讨论】:

        • alert.UserAlerts 可以是 IEnumerable 或 IQueryAble 而不是列表
        • 谢谢,现在说得通了。我无法在 UserAlerts 上运行 RemoveAll,因为它是 ICollection,如何转换为适当的类型?
        • @DavidB 当你施放它时,它将成为新对象
        • @DavidB 如果不是List,你应该使用Where扩展方法并将新值赋给UserAlerts
        • @DavidB 和Where中的否定谓词
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-07-05
        • 2012-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多