LINQ to SQL : How to work with Take keyword

By Mohammad Mahdi Ramezanpour at August 05, 2008 00:53
Filed Under: .NET General, LINQ

As you know, we have a keyword in SQL name TOP that we can use in order to take a limit count of rows in a select statement. Now if you want to use such a thing in LINQ to SQL, you have to use the Take keyword.

Here is an example of using Take keyword:

    var first4Customers = (
                from c in customers

                select new {c.CustomerID, c.CustomerName} )
                .Take(4);

In this example the result will return first 4 records of our Customer table. The equivalent of this code is SQL is something like this:

SELECT TOP(4) CustomerID, CustomerName FROM Customers

When you're using Take keyword the type of result we be equal to a simple select statement. This will return an object from IQueryable(Of T), So that you can use the result like a simple select statement. For example, if you want to return you result set as a List(Of T), you can use the following code:

    var first4Customers = (
                from c in customers

                select new {c.CustomerID, c.CustomerName} )
                .Take(4).ToList();

Note that is doesn't have any difference between this and a simple select statement.

Comments are closed

Currently Reading

Quote of the day

Send Persian SMS