如何将项添加到缓存集合?

时间:2011-03-29 08:22:48

标签: c# asp.net collections viewstate

我想在viewstate中缓存一个集合,但我想知道是否有更好的方法将项添加到此集合中!

private List<MyClass> CachedItems
{
    get { return (List<MyClass>)ViewState["CachedItems"]; }
    set { ViewState["CachedItems"] = value; }
}

private void AddToCachedItems(MyClass item)
{
    CachedItems = CachedItems.Concat(new[] { item }).ToList();
}

1 个答案:

答案 0 :(得分:0)

public List<MyClass> CachedItems
{
    get
    {
        return (List<MyClass>)( ViewState["CachedItems"] = ViewState["CachedItems"] ??
                new List<MyClass>());

    }
}

然后只是

CachedItems.Add(new MyClass());