C# / .NET / ASPX:显示数组中的最后 5 个
本文关键字:最后 显示 NET ASPX 数组 | 更新日期: 2023-09-27 18:34:06
我已经设法将从最近搜索中保存的 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
。
若要从数组中删除最后 5 个元素,可以使用 linq 并跳过前 length-5
个元素,如下所示:
foreach (String searchHist in tokens.Skip(tokens.Length - 5))
{
if(userSettings.Length > refer)
{
output.Append("<li>" + searchHist + "</li>");
}
}
在此之前,您可能需要检查长度是否至少为 5:
int toSkip = tokens.Length - 5;
if (toSkip < 0) toSkip = 0;
foreach (String searchHist in tokens.Skip(toSkip))
...
如果数组始终如下所示,请尝试使用这个而不是foreach
循环: first:second:third:forth:fifth:sixth
,你想要second
、third
、forth
和fifth
:
for (int i = tokens.Length - 6, i < tokens.Length; i++)
{
string searchHist = tokens[i];
if(userSettings.Length > refer)
{
output.Append("<li>" + searchHist + "</li>");
}
}