【发布时间】:2016-02-11 09:05:03
【问题描述】:
我已经成功地将最近搜索中保存的 Cookie 拆分为一个包含所有最近搜索的数组,我现在只想取出最后 5 个搜索,这将是数组中的最新搜索
到目前为止我有:
var output = new StringBuilder();
if (Request.Cookies["UserSettings"] != null)
{
string userSettings = Request.Cookies["UserSettings"].Value;
output.Append("<div style='float: right; width: 55%;'> Your recently searched: <ul>");
{
try
{
string[] tokens = userSettings.Split(':');
int count = 0;
int refer = userSettings.Length - 5;
foreach (String searchHist in tokens)
{
if(userSettings.Length > refer)
{
if (count > 4)
{
output.Append("<li>" + searchHist + "</li>");
}
count++;
}
}
}
catch (Exception ex)
{
output.Append("<li>" + userSettings + "</li>");
}
finally
{
output.Append("</div>");
recentSearch.Text = output.ToString();
}
}
}
但这似乎只是跳过了数组中的前 5 个。有没有更简单的方法来拉出数组中的最后 5 个字符串?非常感谢。
编辑:数组看起来像这样 - first:second:third:forth:fifth:sixth 所以在这种情况下,我需要它来显示:second third forth 和 fifth。
【问题讨论】:
-
查看此处了解从可枚举中获取最后一个
n元素的好方法:stackoverflow.com/questions/3453274/… -
谢谢,所以我的代码看起来像这样:
tokens.Skip(Math.Max(0, tokens.Count() - 5));在try中,但我在哪里可以AppendCookie 中保存的字符串? @Ric