Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove oldest n Items from List using C#

Tags:

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).

like image 337
mikedugan Avatar asked Jun 05 '13 04:06

mikedugan


3 Answers

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.

like image 181
Blorgbeard Avatar answered Sep 23 '22 23:09

Blorgbeard


Try this

scoreList.RemoveAt(scoreList.Count-1);

And here is the MSDN Article

like image 25
PraveenVenu Avatar answered Sep 23 '22 23:09

PraveenVenu


Instead of using a List<int> I would recommend using a Queue<int>. That will give you the FIFO behavior you're looking for.

See http://msdn.microsoft.com/en-us/library/7977ey2c.aspx for more information on Queues.

  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();
  }
like image 7
Jaaromy Zierse Avatar answered Sep 22 '22 23:09

Jaaromy Zierse