2

hello I am creating a web app in which i have a session which is consist of my array string i want to add more items in that particular session

    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 
        }
    }
tereško
  • 58,060
  • 25
  • 98
  • 150
  • 1
    Don't use an array - it won't grow. And never add to a collection you're iterating over. – bommelding Sep 24 '18 at 12:07
  • You can't add items to array. Check this link https://stackoverflow.com/questions/1440265/how-to-add-a-string-to-a-string-array-theres-no-add-function – Ahmet Taşgöz Sep 24 '18 at 12:09

2 Answers2

4

Session is a store so you can't simply create a reference to the objects within it to update them.

You will need to read the list from session and assign to a local variable. Update this variable and finally add the local variable back into session to overwrite the one that is there.

If you use a generic list, you can use the Add or AddRange methods to add anywhere in the list

0

Arrays can't grow in length, so you are better off using another data structure. But if you insist on using arrays you need to create a new Array and then assign it to the session variable.

You can do something like this using 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();
}
themehio
  • 38
  • 7