在数组c#的现有会话中添加字符串数组

时间:2018-09-24 12:03:33

标签: c# arrays asp.net-mvc session

你好,我正在创建一个Web应用程序,其中有一个会话,该会话由数组字符串组成,我想在该特定会话中添加更多项

    if (System.Web.HttpContext.Current.Session["Questions"] == null)
    {
        System.Web.HttpContext.Current.Session["Questions"] = Questions; // here question is string array, 
        //assigning value of array to session if session is null
    }
    else
    {
        for (var i = 0; i < ((string[])System.Web.HttpContext.Current.Session["Questions"]).Length; i++)
        {
           // what i need to do to push other item in the present session array
           //wants to add Question here 
        }
    }

2 个答案:

答案 0 :(得分:4)

会话是商店,因此您不能简单地创建其中的对象的引用来更新它们。

您将需要从会话中读取列表并分配给本地变量。更新此变量,最后将局部变量添加回会话中,以覆盖其中的那个变量。

如果使用通用列表,则可以使用Add或AddRange方法在列表中的任意位置添加

答案 1 :(得分:0)

数组的长度不能增加,因此最好使用其他数据结构。 但是,如果您坚持使用数组,则需要创建一个新的Array,然后将其分配给session变量。

您可以使用Linq执行以下操作:

if (System.Web.HttpContext.Current.Session["Questions"] == null)
{
    System.Web.HttpContext.Current.Session["Questions"] = Questions; // here question is string array, 
    //assigning value of array to session if session is null
}
else
{
    string[] newQuestions = { "how are you?", "how do you do?" };
    string[] existingQuestions = (string[])HttpContext.Current.Session["Questions"];
    HttpContext.Current.Session["Questions"] = newQuestions.Union(existingQuestions).ToArray();
}