c# 查询历史记录6条 超过6条自动删除最后一条代码
时间: 2024-04-12 14:28:44 浏览: 21
你可以使用队列 (Queue<T>) 数据结构来实现查询历史记录的功能,并且保持最多6条记录。当添加新的记录时,如果历史记录已满,则自动删除最早的记录。以下是一个示例代码:
```csharp
using System;
using System.Collections.Generic;
class SearchHistory
{
private Queue<string> history;
private int maxHistoryLength;
public SearchHistory(int maxHistoryLength = 6)
{
history = new Queue<string>();
this.maxHistoryLength = maxHistoryLength;
}
public void Add(string keyword)
{
if (history.Count == maxHistoryLength)
{
history.Dequeue();
}
history.Enqueue(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` 方法中,如果历史记录已满,则使用 `Dequeue` 方法删除最早的记录,并使用 `Enqueue` 方法将新的搜索关键字添加到队列的末尾。 `PrintHistory` 方法用于打印所有历史记录。
你可以根据自己的需求修改代码,并将搜索历史记录的关键字替换为你的实际搜索关键字。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)