Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove 3 oldest elements from a List<> in C#

Tags:

c#

linq

Let's say I have an object:

public class CustomObj
{
    DateTime Date { get; set; }
    String Name { get; set; }
}

Then let's say I have a List with 20 various elements.

var stuff = new List<CustomObj>
{
    { Date = DateTime.Now, Name = "Joe" },
    { Date = DateTime.Now.AddDays(1), Name = "Joe2" },
    { Date = DateTime.Now.AddDays(2), Name = "Joe3" },
    { Date = DateTime.Now.AddDays(3), Name = "Joe4" },
    { Date = DateTime.Now.AddDays(4), Name = "Joe5" },
    { Date = DateTime.Now.AddDays(5), Name = "Joe6" },
    { Date = DateTime.Now.AddDays(6), Name = "Joe7" },
    { Date = DateTime.Now.AddDays(7), Name = "Joe8" },
    { Date = DateTime.Now.AddDays(8), Name = "Joe9" },
    { Date = DateTime.Now.AddDays(9), Name = "Joe10" },
    { Date = DateTime.Now.AddDays(10), Name = "Joe11" }
}

How can I remove the 3 oldest elements?

stuff.RemoveAll(item => ???)
like image 256
David Avatar asked Nov 08 '09 07:11

David


2 Answers

If you only need to enumerate the items, this will work:

stuff.OrderBy(item => item.Date).Skip(3);

If you actually want it in list form you will have to call .ToList() afterwards:

stuff = stuff.OrderBy(item => item.Date).Skip(3).ToList();
like image 191
John Rasch Avatar answered Oct 04 '22 22:10

John Rasch


If you're willing to replace the list with a new one, you could try this:

stuff = stuff.OrderBy( c => c.Date).Skip(3).ToList();

On the other hand, if you need stuff to remain the same exact List<T> instance, you could sort it and then remove a range by index:

stuff.Sort(...);
stuff.RemoveRange(0, 3);
like image 28
Bevan Avatar answered Oct 04 '22 22:10

Bevan