Limiting the Number of Results from LINQ

LINQ is great for selecting data. But how can you limit the number of items returned from a LINQ expression? In MySQL, we use the LIMIT n clause with a number indicating that MySQL should return the first n rows.

In LINQ, this functionality is available via the Take keyword. For example, this code:


List overPaidEmployees = Employee.Find(e => e.Salary >= 100000)
.OrderBy(e => e.Name)
.Take(3)
.ToList();

… would return the the employees (by name) who are paid a salary of $100,000 or more.

About Ashiq Alibhai, PMP

Ashiq has been coding C# since 2005. A desktop, web, and RIA application developer, he's touched ASP.NET MVC, ActiveRecord, Silverlight, NUnit, and all kinds of exciting .NET technologies. He started C# City in order to accelerate his .NET learning.
This entry was posted in Core .NET, Silverlight, Web, Wndows Forms, WPF and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *