繁体   English   中英

未从清单中删除的项目

[英]Items not removed from List

我有以下代码。 在我的测试计划列表集合中有150个项目。 删除后计数为75,这意味着从列表中删除了75个项目。 为什么在该countItems列表之后是​​150。似乎没有从列表中删除项目。 为什么? 我如何从列表中删除项目。

...
planList = (IList<UserPlanned>)_jsSerializer.Deserialize(plannedValues,typeof(IList<UserPlanned>));
int count = planList.ToList().RemoveAll(eup => eup.ID <= -1);
int countItems = planList.Count;
...

调用ToList()时,它将复制您的列表,然后从复制中删除项目。 采用:

int count = planList.RemoveAll(eup => eup.ID <= -1);  

实际上,您是从ToList方法创建的列表中删除元素,而不是从planList本身中删除元素。

ToList()正在创建要从中删除项目的其他列表。 这实际上是您正在执行的操作:

var list1 = (List<UserPlanned>)_jsSerializer.Deserialize(plannedValues,typeof(List<UserPlanned>));
var list2 = list1.ToList(); // ToList() creates a *new* list.

list2.RemoveAll(eup => eup.Id <= -1);

int count = list2.Count;
int count2 = list1.Count;
var templst = planList.ToList();
int count = templst.RemoveAll(eup => eup.ID <= -1);
int countItems = templst.Count;

那应该工作。 如上所述,tolist命令创建一个新列表,从中删除值。 我不知道您的planList的类型,但是如果它已经是一个List,则可以简单地省略.tolist

int count = planList.RemoveAll(eup => eup.ID <= -1);

请问摇摇欲坠的C#,我通常在写vb.net

planList = (List<UserPlanned>)_jsSerializer.Deserialize(plannedValues,typeof(List<UserPlanned>));
int count = planList.RemoveAll(eup => eup.ID <= -1);
int countItems = planList.Count;

删除ToList() 这将在内存中创建一个新列表,因此您实际上不会更新基础列表。 您也不需要它。

planList尚未更改。

planList.ToList()  //This creates a new list.
.RemoveAll()       //This is called on the new list.  It is not called on planList.

planList.ToList()创建一个操作RemoveAll的新列表。 它不会修改IEnumerable planList。

尝试这样的事情:

planList = (List<UserPlanned>)_jsSerializer
     .Deserialize(plannedValues,typeof(List<UserPlanned>))
    .ToList();
int count = planList.RemoveAll(eup => eup.ID <= -1);
int countItems = planList.Count;

如果您使用的是JavaScriptSerializer,请http://msdn.microsoft.com/zh-cn/library/bb355316.aspx_,然后尝试以下操作:

planList = _jsSerializer.Deserialize<List<UserPlanned>>(plannedValues);

int count = planList.RemoveAll(eup => eup.ID <= -1);
int countItems = planList.Count;

该代码应类似于

lanList = (List<UserPlanned>)_jsSerializer.Deserialize(plannedValues,typeof(List<UserPlanned>));

int count = planList.RemoveAll(eup => eup.ID <= -1);

int countItems = planList.Count;

暂无
暂无

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

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