List<> remove item issue
We are using List<object>
type as datasource for dropdownlist.
Process flow:
- Assign value (
List<objec开发者_如何学运维t>
) to the session in the pageload event(!ispostback
). - Retrieve value from session in
ddl_SelectedIndexChanged
event - Remove a particular item from the list and bind to the ddl
Code:
List<Loc> locList = new List<Loc>();
locList = (List<Loc>)Session["Loc"];
locID = "xxx";
locList.RemoveAt(locList.FindIndex(FindLocation));
Problem:
Item is getting removed from the base source also (session).
The problem is that you're manipulating the list that is stored in the session, not a copy. Instead, if you do something like this:
List<Loc> locList = new List<Loc>((List<Loc>)Session["Loc"]);
locID = "xxx";
locList.RemoveAt(locList.FindIndex(FindLocation));
you're operating on a copy of the list, and the original won't change.
It sounds like you are storing the list in session, fetching it out, and mutating it. Actually, you might see different results if you switch from the in-process state to distributed state or database state.
The problem is that with in-process state there is only one list. It isn't serialized / deserialized, so when you remove an item it stays removed. You could clone the list easily enough:
locList = new List<Loc>(locList);
which should solve this. With the other state implementations the data is serialized, and each deserialized copy is separate, so you won't see this. But I wouldn't depend on the state implementation. Personally I've never understood why such behaviour-changing subtleties are allowed with state; I would have preferred it to always serialize/deserialize, even when in-process.
精彩评论