[英]Remove oldest n Items from List using 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
}
如果有人可以幫助它,將不勝感激:)我不得不使代碼有點通用,因為它是相當隱秘地編寫的(沒有編寫方法)。
使用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);
}
您從列表的開頭刪除,因為Add
項目時它們會移到末尾-因此最早的是在開頭。
我建議不要使用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();
}
我不太了解您的問題,希望這就是您想要的。
scoreList.RemoveRange(Items.Count()*3, scoreList.Count()-Items.Count()*3);
一種使用linq從列表中獲取最后n個元素的簡單方法
scoreList.Skip(Math.Max(0, scoreList.Count() - N)).Take(N)
我scoresList.RemoveAt()
看了看上面建議的方法( scoresList.RemoveAt()
),但是它不適合這種情況。 最終結果是什么:
if (...)
{
scoresList.RemoveRange(0, scores.Count);
}
謝謝你們的幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.