deleting a bunch of session with different names in c#

Advertisements

I know how to delete session in c#

Session.Remove("SessionName");

How is that possible to delete all the sessions which conatin YYY in their name in c#?
for example

YYY_1
YYY_2 .....

>Solution :

Yeah you can delete all the sessions which contains YYY in it using this method:

List<string> keysToRemove = new List<string>();

foreach (var key in Session.Keys)
{
    if (key is string && key.ToString().Contains("YYY"))
    {
        keysToRemove.Add(key.ToString());
    }
}

foreach (var key in keysToRemove)
{
    Session.Remove(key);
}
  • Here we iterate over all session keys using Session.Keys.
  • Here we check if each key is a string and contains the specified substring ("YYY").
  • If a key matches the criteria, we add it to a list (keysToRemove).
  • Finally, we iterate over the list of keys to remove and call Session.Remove for each key.

Ref : https://dotnetfiddle.net/SUGUqE

Leave a ReplyCancel reply