Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 打印添加到字符串列表的最后3个元素_C# - Fatal编程技术网

C# 打印添加到字符串列表的最后3个元素

C# 打印添加到字符串列表的最后3个元素,c#,C#,我有一个字符串列表,我不断地向这个列表添加元素。 我不希望此列表增长超过6个元素(索引0到5)。因此,一旦它到达索引[5],我不想增加列表,而是在列表的开头添加元素或做类似的事情。在任何时候,我都会按上次添加到此列表的项目顺序打印添加到此列表的最后3个项目。我在下面尝试过,但我认为这是一段糟糕的代码。在这段代码之后,我将获得列表计数并打印urlist[urlist.count-1],urlist[urlist.count-2];,UrlList[UrlList.Count-3] 请帮帮我

我有一个字符串列表,我不断地向这个列表添加元素。 我不希望此列表增长超过6个元素(索引0到5)。因此,一旦它到达索引[5],我不想增加列表,而是在列表的开头添加元素或做类似的事情。在任何时候,我都会按上次添加到此列表的项目顺序打印添加到此列表的最后3个项目。我在下面尝试过,但我认为这是一段糟糕的代码。在这段代码之后,我将获得列表计数并打印
urlist[urlist.count-1],urlist[urlist.count-2];,UrlList[UrlList.Count-3]
请帮帮我

     if (UrlList.Count == 5)
    {
        var move = UrlList[5];
        UrlList.RemoveAt(5);
        UrlList.Insert(0, move);

         move = UrlList[4];
        UrlList.RemoveAt(4);
        UrlList.Insert(1, move);

         move = UrlList[3];
        UrlList.RemoveAt(3);
        UrlList.Insert(2, move);
         UrlList.Add(uri.ToString());
    }

    else
    {
        UrlList.Add(uri.ToString());
    }
如果希望最新的项目是列表中的最后一个项目,可以使用以下代码:

const int Max_Capacity = 6;

if (UrlList.Count >= Max_Capacity) 
  UrlList.RemoveAt(0); // <- oldest (first) item should be removed

UrlList.Add(uri.ToString());

...

// Printing out the lastest 3 items:
int start = UrlList.Count <= 3 ? 0 : UrlList.Count - 3;

for (int i = start; i < UrlList.Count; ++i)
  Console.Out.WriteLine(UrlList[i]);
const int Max_容量=6;
如果(urlist.Count>=最大容量)

UrlList.RemoveAt(0);// 我想你最好使用%Operator-

在您的情况下,您可以使用:

UrlList.Insert((UrlList.count%6),move); 

您是否一直在列表中添加3项?或者你可以在任何给定的时间添加1-5个元素吗?我将元素1乘1添加到列表中。。但一次打印3个-最后一个元素,最后一个元素-1,最后一个元素-2