Challa Jyothi
Challa Jyothi

Reputation: 241

how to not delete a single particular session variable?

I have a problem with deleting session variables..

Assume I have 30 session variables...I want to delete 29 session variables but one.How can I do this please help me!

I tried Session.RemoveAll() With this it deletes ALL the sessions.But my required requirement is to delete all but ONE Session.How do i do it?

Upvotes: 1

Views: 1736

Answers (2)

शेखर
शेखर

Reputation: 17604

You can use Session.Remove to remove using key from the session collection.

You can loop through you session collection

for (int i = 0; i < Session.Contents.Count; i++)
{
      var key = Session.Keys[i];
      var value = Session[i];

      //remove the key except one
      if(key!="youkey")
           Session.Remove(key);

}

Edit 1

As suggested by @JoachimIsaksson

 for (int i = 0; i < Session.Contents.Count; i++)
 {
      var key = Session.Keys[i];
      var value = Session[i];

      //remove the key except one
      if(key!="youkey")
      {
           Session.Remove(key);
           i++;
       }

 }

Edit 2

As suggested by @JoachimIsaksson I am not sure right one or not

 for (int i = 0; i < Session.Contents.Count; i++)
 {
      var key = Session.Keys[i];
      var value = Session[i];

      //remove the key except one
      if(key!="youkey")
      {
           Session.Remove(key);
           i--;
       }

 }

Upvotes: 4

Joachim Isaksson
Joachim Isaksson

Reputation: 181077

You could just simply save the variable you want to keep, clear all and put it back;

var value = Session["tokeep"]; 
Session.RemoveAll(); 
Session["tokeep"] = value;

Upvotes: 1

Related Questions