0

次のコードがあります。私のテストplanListコレクションには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;
...
4

8 に答える 8

6

ToList()を呼び出すと、リストがコピーされ、コピーからアイテムが削除されます。使用する:

int count = planList.RemoveAll(eup => eup.ID <= -1);  
于 2012-10-29T16:21:59.273 に答える
3

実際には、planList自体からではなく、ToListメソッドによって作成されたリストから要素を削除しています。

于 2012-10-29T16:22:02.523 に答える
1

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;
于 2012-10-29T16:24:06.780 に答える
1
var templst = planList.ToList();
int count = templst.RemoveAll(eup => eup.ID <= -1);
int countItems = templst.Count;

それはうまくいくはずです。上記のように、tolistコマンドは新しいリストを作成し、そこから値が削除されます。planListのタイプはわかりませんが、すでにリストになっている場合は、.tolistを省略できます。

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

不安定なc#を失礼します、私は通常vb.netを書いています

于 2012-10-29T16:24:23.927 に答える
0
planList = (List<UserPlanned>)_jsSerializer.Deserialize(plannedValues,typeof(List<UserPlanned>));
int count = planList.RemoveAll(eup => eup.ID <= -1);
int countItems = planList.Count;

を削除しToList()ます。これはメモリ内に新しいリストを作成するため、基になるリストを実際に更新することはありません。あなたもそれを必要としません。

于 2012-10-29T16:23:20.127 に答える
0

planListは変更されていません。

planList.ToList()  //This creates a new list.
.RemoveAll()       //This is called on the new list.  It is not called on planList.
于 2012-10-29T16:23:22.123 に答える
0

planList.ToList()は、RemoveAllが操作する新しいリストを作成します。IEnumerableplanListは変更されません。

次のようなものを試してください。

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/en-us/library/bb355316.aspx_ 次に、次のことを試してください。

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

int count = planList.RemoveAll(eup => eup.ID <= -1);
int countItems = planList.Count;
于 2012-10-29T16:26:05.823 に答える
0

コードは次のようになります

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

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

int countItems = planList.Count;
于 2012-10-29T16:33:45.867 に答える