Eugene
Eugene

Reputation: 97

How can I specify the range of rows my LINQ query should retrieve

I have the following LINQ query:

List<Person> people = 
                db.People.Take(pageSize)
                .OrderByDescending(t => t.Id)
                .ToList();

The goal is to specify range of rows which should be get. I want to do it with where statement. The question is how is it possible to put specific indexes of rows into the where statement?

Something like this:

List<Person> people = 
                    db.People.Take(pageSize)
                    .Where(t => t.startIndex > 55 and t => t.endIndex < 60)
                    .OrderByDescending(t => t.Id)
                    .ToList();

Upvotes: 1

Views: 89

Answers (2)

Scotty
Scotty

Reputation: 1137

public static List<Person> GetPeopleRange(int pageSize, int startIndex, int endIndex)
    {
        using (var db = new MyEntities())
        {
            return (from p in db.People
                    .Where(p => p.Id >= startIndex && p.Id < endIndex)
                        select p).Take(pageSize).OrderByDescending(p => p.Id).ToList();
        }
    }

Upvotes: 0

Nic
Nic

Reputation: 12846

You could use skip and take, something like this:

List<Person> people = db.People
                        .Skip(pageSize * pageNumber).Take(pageSize)
                        .OrderByDescending(t => t.Id)
                        .ToList();

Upvotes: 1

Related Questions