I have a list of items (linq to sql), which can be ordered by various properties, not just by Id asc/desc
If the list was ordered only by Id
,
I could call list.Where(o => o.Id > 123).Take(10)
is there any linq methods/functionality that would allow to ?
Take 10 items after id with value = 123
SQL has no concept of row ordering so it you can't request after a particular row from SQL. However, LINQ to Objects does so you can use that:
If list
is a List<T>
created from your query, just use SkipWhile
:
list.SkipWhile(o => o.Id != 123).Skip(1).Take(10)
If list
is a LINQ to SQL Query, then first use AsEnumerable
but realize this will bring over the entire query to the client:
list.AsEnumerable().SkipWhile(o => i.Id != 123).Skip(1).Take(10)
If you know the ordering and can test against it, you could filter and reduce the amount of data returned to the client by 1. Computing the maximum duplicates of the ordering for a given Id
and 2. Only returning the records in the desired order that are greater than or equal to the sort value(s) for the desired Id
:
var maxdup = list.GroupBy(o => o.someProp).Select(og => og.Count()).Max();
var ans = list.Orderby(o => o.someProp)
.Where(o => o.someProp >= list.Where(o2 => o2.Id == 123).First().someProp)
.Take(10+maxdup)
.AsEnumerable()
.SkipWhile(o => o.Id != 123).Skip(1)
.Take(10);