'Page-by output. LINQ, Skip() and Take()

I get two items if do like this:

private int page = 0;
private int size = 2;

List<ContractTableRow> rows =
    (from c in model.Contracts
     join w in model.Workers on c.Worker equals w.Id
     where c.Worker == w.Id
     select new ContractTableRow
     {
        ...
     })
     .Skip(page * size)
     .Take(size)
     .ToList();

I get all items if I do:

List<ContractTableRow> rows =
      (from c in model.Contracts
       .Skip(page * size)
       .Take(size)
       join w in model.Workers on c.Worker equals w.Id
       where c.Worker == w.Id
       select new ContractTableRow
       {
          ...
       })
       .ToList();

Why doesn't the second code gives two elements?

What is the sequence of the first code? First select all elements with new ContractTableRow and then skip, take? Or initially skip, take and then select?

I need this to create a page-by output of records from the database. Is it right to implement it this way?



Solution 1:[1]

The right way to do this is, first get rid of the join and use Navigation properties, then the right order is IQueryable.OrderBy.[ThenBy.]Skip.Take.Select. And you must provide an OrderBy that completely orders the results, or else your pages can have gaps and overlaps.

List<ContractTableRow> rows =
       db.Contracts
         .OrderBy( r => r.Id )
         .Skip(page * size)
         .Take(size)
         .Select( c => new ContractTableRow()
           {
              c.Id,
              c.Worker.Name...
           })
         .ToList();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1