Remove 3 oldest elements from list <> in C #

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 different items.

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 to remove the 3 oldest items?

stuff.RemoveAll(item => ???)
+5
source share
5 answers

If you only need to list the elements, this will work:

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

If you really want it in a list form, you will have to call .ToList()after this:

stuff = stuff.OrderBy(item => item.Date).Skip(3).ToList();
+8
source

If you want to replace the list with a new one, you can try the following:

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

On the other hand, if you need stuffto remain the same exact instance List<T>, you can sort it and then delete the range by index:

stuff.Sort(...);
stuff.RemoveRange(0, 3);
+4

, RemoveRange:

int n = 3;
stuff.RemoveRange(stuff.Count - n, n);
+3
const int cToRemove = 3;

var top3 = (from c in stuff
        orderby c.Date ascending
        select c).Take(cToRemove);
+1

, O (n log n), .

, O (n), . MinBy MoreLINQ - , , ( RemoveAt Remove).

// The list.Count part is in case the list starts off with
// fewer than 3 elements
for (int i = 0; i < 3 && list.Count > 0; i++)
{
    var oldest = list.MinBy(x => x.Date);
    list.Remove(oldest);
}

, , , , , . O (n), , , 6 :)

+1

All Articles