Delete the last N entries, Entity Framework

I use the following code to delete the last N entries in the Entity Framework:

Extension method for receiving the last N elements taken from here :

public static IEnumerable<T> TakeLast<T>(this IEnumerable<T> source, int N)
{
    return source.Skip(Math.Max(0, source.Count() - N));
}

Delete the last N items:

MyDbContext.MyDbSet.RemoveRange(MyDbContext.MyDbSet.TakeLast(N));

Is it effective? I do not want to reinvent the wheel. Perhaps I missed some existing function like collection.RemoveLast (although I could not find it with my first effort)?

+4
source share
3 answers

, , . RemoveRange() . , n , . TakeLast() , .

+1

:

var lastN = MyDbContext.MyDbSet
                       .OrderByDescending(g => g.Id)
                       .Take(N);

MyDbContext.MyDbSet.RemoveRange(lastN);
+1

-

var lastUser = MyDbContext.Users.Select(g => g.Id).Max();

. , , . , , , .

MyDbContext.Users.Remove(lastUser);
MyDbContext.SaveChanges();
0
source

All Articles