I’m using a generic List to store a set of data in the viewstate. If I try sorting the list using linq in the get accessor then when I try to add a new item to the list if doesn’t work. No error, it just doesn’t add it to the list.
When I run this line of code:
MyObjectList.Add(new MyObject());
using this property doesn’t work:
public List<MyObject> MyObjectList
{
get
{
if (ViewState["MyObjectList"] == null)
ViewState["MyObjectList"] = GetDataFromDataBase();
return ((List<MyObject>)ViewState["MyObjectList"]).OrderBy(x => x.MyObjectID).ToList();
}
}
but using this property does (although now I have to sort every time after getting):
public List<MyObject> MyObjectList
{
get
{
if (ViewState["MyObjectList"] == null)
ViewState["MyObjectList"] = GetDataFromDataBase();
return (List<MyObject>)ViewState["MyObjectList"];
}
}
How am I supposed to sort the data in the get accessor?
.ToList creates a copy of the list. You are adding to that rather than the original list.