leora
leora

Reputation: 196469

How do i return a certain max number of items from a collection using linq

I have code below that builds a collection and returns it sorted by a property

var appChanges = GetHistory().ToList();
return appChanges.OrderByDescending(r => r.Change.When);

i want this to only return a max of 50 items (or total if collection size is less than 50)

how can i do this in LINQ ?

Upvotes: 1

Views: 188

Answers (3)

Nick Larsen
Nick Larsen

Reputation: 18877

Use the .Take(...) function.

You can also use .Skip(..) in conjunction with it for paging queries.

Also, you'll want to avoid using .ToList() so early if you can avoid it because it will evaluate the query and return a result set.

Upvotes: 4

Rob
Rob

Reputation: 5603

You're looking for Take. See http://msdn.microsoft.com/en-us/library/bb503062.aspx

appChanges.OrderByDescending(r => r.Change.When).Take(50);

Upvotes: 4

desco
desco

Reputation: 16782

return appChanges.OrderByDescending(r => r.Change.When).Take(n);

Upvotes: 2

Related Questions