【问题标题】:adding string array in existing session of array c#在数组c#的现有会话中添加字符串数组
【发布时间】:2018-09-24 12:03:32
【问题描述】:

您好,我正在创建一个 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 
        }
    }

【问题讨论】:

  • 不要使用数组——它不会增长。并且永远不要添加到您正在迭代的集合中。
  • 您不能将项目添加到数组中。检查此链接stackoverflow.com/questions/1440265/…

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


【解决方案1】:

Session 是一个存储,因此您不能简单地创建对其中对象的引用来更新它们。

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

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

【讨论】:

    【解决方案2】:

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

    你可以使用 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();
    }
    

    【讨论】:

      猜你喜欢
      • 2016-01-22
      • 1970-01-01
      • 1970-01-01
      • 2013-05-07
      • 2017-06-25
      • 2023-01-19
      • 1970-01-01
      • 2011-04-03
      • 2015-03-23
      相关资源
      最近更新 更多