Learning Learning - 5 months ago 23
C# Question

How to skip last 2 records and get all other records with linq?

I have a table called Test:

Test: Id, CreatedBy, CreatedDate

Now I want to get list of test but
skip last 2 test
. So if I have say for e.g.
10 test
then I want to get 1 - 8 test and skip test 9 and 10.

This is how I am trying to do that:

var query = context.Test.OrderByDescending(t=>t.Id).Skip(2) // How to take other records?

Can anybody please help me with this?


In this case: Take(8)

With Take and Skip you can get any range you want.


var query = context.Test.OrderByDescending(t=>t.Id);
var allButTheLastTwoElements = query.Take(query.Count() - 2);

Safest way:

var query = context.Test.OrderByDescending(t=>t.Id).ToList();
var allButTheLastTwoElements = query.Take(Math.Max(0,query.Count() - 2));

Or you could just do it the other way around (depending on your requirements)

var query = context.Test.OrderByAscending(t=>t.Id).Skip(2);