使用C#从列表中删除最后N个项目 [英] Remove Last n Items from List using C#
问题描述
我的工作成绩是经常更新的动态清单。最终这是用于生产的整体评价,所以旧条目(基于一些参数,而不是时间)需要被去除,以防止重上的+/-总体加权。它会立即从单独的枚举被添加多个值
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).
推荐答案
使用的 列表< 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屋!