I have Session["ID"]="1,2,3,4,5"
.
How I remove a single value(2 or any) from Session?
If you wanna remove first value, you can use;
var s = "1,2,3,4,5";
var result = string.Join(",", s.Split(',').Skip(1).ToList());
Console.WriteLine(result); // 2,3,4,5
If you wanna remove last value,
var s = "1,2,3,4,5";
var lastValue = s.Split(',')[s.Split(',').Length - 1];
var result = string.Join(",", s.Split(',').TakeWhile(c => !string.Equals(c, lastValue)).ToList());
Console.WriteLine(result); // 1,2,3,4
Its ugly, but you could try the following:
var numberToRemove = 3
var result = Session["ID"]
.Replace(numberToRemove.ToString(), string.Empty)
.Replace(",,",",")
.Trim(',');
Session["ID"] = result;
or
var result2 = Session["ID"]
.Split(',')
.Where(s => s != numberToRemove.ToString())
.Aggregate((s1, s2) => s1 += "," + s2);
You can split the string using the delimiter remove the items and then join the remaining strings using the delimiter
var sessionIds = Session["ID"].Split(',').ToList();
sessionIds.Remove("1");
sessionIds.Remove("5");
Session["ID"] = string.Join(",", sessionIds);
You an use Regex for that:
Session["ID"] = Regex.Replace(Session["ID"], "[15],|,[15]$", string.Empty);
Maybe there are whitespaces after each colon:
Session["ID"] = Regex.Replace(Session["ID"], "\s*[15],|,\s*[15]$", string.Empty);
string GetID = txtID.text;
var sessionIds = Session["ID"].ToString().Split(',').ToList();
sessionIds.Remove(GetID);
Session["ID"] = string.Join(",", sessionIds);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.