c#搜索历史记录,固定六条,增加的话替换最后一条
时间: 2023-10-28 20:43:39 浏览: 31
你可以使用 List<T> 数据结构来保存搜索历史记录,并且通过控制列表的长度来实现固定六条记录并替换最后一条的功能。以下是一个示例代码:
```csharp
using System;
using System.Collections.Generic;
class SearchHistory
{
private List<string> history;
private int maxHistoryLength;
public SearchHistory(int maxHistoryLength = 6)
{
history = new List<string>();
this.maxHistoryLength = maxHistoryLength;
}
public void Add(string keyword)
{
if (history.Count == maxHistoryLength)
{
history.RemoveAt(history.Count - 1);
}
history.Insert(0, keyword);
}
public void PrintHistory()
{
foreach (string keyword in history)
{
Console.WriteLine(keyword);
}
}
}
class Program
{
static void Main(string[] args)
{
SearchHistory searchHistory = new SearchHistory();
searchHistory.Add("keyword1");
searchHistory.Add("keyword2");
searchHistory.Add("keyword3");
searchHistory.Add("keyword4");
searchHistory.Add("keyword5");
searchHistory.Add("keyword6");
searchHistory.Add("keyword7");
searchHistory.PrintHistory();
}
}
```
以上代码创建了一个 `SearchHistory` 类来管理搜索历史记录。在 `Add` 方法中,如果历史记录已满,则移除最后一条记录,并将新的搜索关键字插入到列表的开头。 `PrintHistory` 方法用于打印所有历史记录。
你可以根据自己的需求修改代码,并将搜索历史记录的关键字替换为你的实际搜索关键字。
相关推荐
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)