
Question:
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 ?
Solution:1
You're looking for Take. See http://msdn.microsoft.com/en-us/library/bb503062.aspx
appChanges.OrderByDescending(r => r.Change.When).Take(50);
Solution:2
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.
Solution:3
return appChanges.OrderByDescending(r => r.Change.When).Take(n);
Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
EmoticonEmoticon