使用C#从列表中删除最旧的n个项目

mik*_*gan 35 c#

我正在研究经常更新的动态分数列表.最终,这用于产生总体评级,因此需要删除较旧的条目(基于某些参数,而不是时间)以防止对整体进行重度+/-加权.它将从单独的枚举中一次添加多个值.

  List<int> scoreList = new List<int>();

  foreach(Item x in Items)
  { 
     scoreList.Add(x.score);
  }

  //what I need help with:
  if(scoreList.Count() > (Items.Count() * 3))
  {
      //I need to remove the last set (first in, first out) of values size 
      //Items.Count() from the list
  }
Run Code Online (Sandbox Code Playgroud)

如果有人可以帮助它将非常感激:)我不得不使代码有点通用,因为它写得相当密码(没有编写方法).

Blo*_*ard 41

使用List<T>.RemoveRange- 像这样:

// number to remove is the difference between the current length
// and the maximum length you want to allow.
var count = scoreList.Count - (Items.Count() * 3);
if (count > 0) {
    // remove that number of items from the start of the list
    scoreList.RemoveRange(0, count);
}
Run Code Online (Sandbox Code Playgroud)

你从列表的开头删除,因为当你的Add项目他们走到最后 - 所以最老的是在开始.


Pra*_*enu 26

试试这个

scoreList.RemoveAt(scoreList.Count-1);
Run Code Online (Sandbox Code Playgroud)

这里是MSDN文章

  • 这将删除最近添加的项目.OP想要删除最旧的项目 (2认同)

Jaa*_*rse 7

而不是使用List<int>我会建议使用Queue<int>.这将为您提供您正在寻找的FIFO行为.

有关队列的更多信息,请参见http://msdn.microsoft.com/en-us/library/7977ey2c.aspx.

  Queue<int> scoreList = new Queue<int>();

  foreach(Item x in Items)
  { 
     scoreList.Enqueue(x.score);
  }

  //Or you can eliminate the foreach by doing the following
  //Queue<int> scoreList = new Queue<int>(Items.Select(i => i.score).ToList());

  //Note that Count is a property for a Queue
  while (scoreList.Count > (Items.Count() * 3))
  {
     scoreList.Dequeue();
  }
Run Code Online (Sandbox Code Playgroud)