What's the Linq to SQL equivalent to TOP or LIMIT/OFFSET?

Viewed 182462

How do I do this

Select top 10 Foo from MyTable

in Linq to SQL?

13 Answers

Use the Take method:

var foo = (from t in MyTable
           select t.Foo).Take(10);

In VB LINQ has a take expression:

Dim foo = From t in MyTable _
          Take 10 _
          Select t.Foo

From the documentation:

Take<TSource> enumerates source and yields elements until count elements have been yielded or source contains no more elements. If count exceeds the number of elements in source, all elements of source are returned.

Use the Take(int n) method:

var q = query.Take(10);

This works well in C#

var q = from m in MyTable.Take(10)
        select m.Foo

I do like this:

 var dados =  from d in dc.tbl_News.Take(4) 
                orderby d.idNews descending

                select new 
                {
                    d.idNews,
                    d.titleNews,
                    d.textNews,
                    d.dateNews,
                    d.imgNewsThumb
                };

This way it worked for me:

var noticias = from n in db.Noticias.Take(6)
                       where n.Atv == 1
                       orderby n.DatHorLan descending
                       select n;
Related