使用C#从列表中删除最旧的n个项目 [英] Remove oldest n Items from List using C#

查看:37
本文介绍了使用C#从列表中删除最旧的n个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on a dynamic listing of scores which is frequently updated. Ultimately this is used to produce an overall rating, so older entries (based on some parameters, not time) need to be removed to prevent heavy +/- weighting on the overall. It will be adding multiple values at once from a separate enumeration.

  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
  }

如果有人可以提供帮助,将不胜感激:)我不得不使代码有点通用,因为它是用相当神秘的方式编写的(没有编写方法).

If anyone can help it would be much appreciated :) I had to make the code a bit generic because it is written rather cryptically (didn't write the methods).

推荐答案

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

Use List<T>.RemoveRange - something like this:

// 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);
}

您从列表的开头删除,因为当您添加项时,它们会移到末尾-因此最早的是在开头.

You remove from the start of the list, because when you Add items they go to the end - so the oldest are at the start.

这篇关于使用C#从列表中删除最旧的n个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆