简体   繁体   English

名单 <T> RemoveAll()不会删除项目

[英]List<T> RemoveAll() isn't removing items

I have an object that looks like this: 我有一个看起来像这样的对象:

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

This is passed to web API and bound correctly to: 这将传递给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; }

I then run the following, expecting the UserAlert with an ID of two to be removed, but the object is unchanged. 然后我运行以下命令,期望删除ID为2的UserAlert,但对象不变。

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

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

The second query is simpler but this doesn't do anything either. 第二个查询更简单,但这也没有做任何事情。 I can't figure out where I'm going wrong. 我无法弄清楚我哪里出错了。

It's because by using ToList you are creating new List object and then remove items form it, not from original IEnumerable. 这是因为通过使用ToList您正在创建新的List对象,然后从表单中删除项目,而不是从原始IEnumerable中删除。

Try using this: 试试这个:

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

You can't run RemoveAll on IEnumerable , so I think using Linq here is a good idea. 你不能在IEnumerable上运行RemoveAll ,所以我认为在这里使用Linq是个好主意。 You will have collection of items which do not have UserId=2 , which is equivalent to removing all items with UserId=2 . 您将拥有没有UserId=2的项目集合,这相当于删除UserId=2所有项目。 You need to reverse your query from RemoveAll and it will work in any case. 您需要从RemoveAll反转您的查询,它将在任何情况下都有效。

That should certainly remove the elements, but I don't see how you would even notice whether it had or not? 那当然应该删除元素,但我不知道你怎么会注意到它是否有?

First you create the list with ToList() and then you call RemoveAll() to remove some elements from that list, but since you haven't stored that list anywhere, you're just going to get the number of items removed back. 首先使用ToList()创建列表,然后调用RemoveAll()从该列表中删除一些元素,但由于您没有将该列表存储在任何位置,因此您只需要删除已删除的项目数。

You have to call RemoveAll on alert.UserAlerts , because ToList creates a new collection. 您必须在alert.UserAlerts上调用RemoveAll ,因为ToList会创建一个新集合。
If you remove all items of that collection, it does not change UserAlerts . 如果删除该集合的所有项目,则不会更改UserAlerts

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

Update: 更新:
If UserAlerts is not a List , use the Where extension method (as wudzik said in his answer): 如果UserAlerts不是List ,请使用Where扩展方法(正如wudzik在他的回答中所说):

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

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM