Zach
Zach

Reputation: 447

Calling LINQ methods on IEnumerable results in empty List

I'm trying to implement pagination on an ASP.NET Repeater control by using LINQ on a Datatable. I expected this code to give me back a page of rows based on parameters currentPage and pageSize:

IEnumerable<DataRow> allRows = allRecordsDataTable.AsEnumerable();
List<DataRow> pageOfRows = new List<DataRow>();

if (allRows.Any())
{
    pageOfRows = allRows
        .OrderBy(dr => dr[3])
        .Reverse()
        .Skip(currentPage * pageSize)
        .Take(pageSize)
        .ToList();
 }

 if (pageOfRows.Count > 0)
     repeater.DataSource = pageOfRows.CopyToDataTable();
 else
     repeater.DataSource = allRecordsDataTable;

The code falls into the if block, so the IEnumerable does indeed contain DataRows. And yet, the List has a count of zero after the linq calls are made, so the repeater is always bound to allRecordsDataTable. Am I misunderstanding how IEnumerable works?

P.S. The .orderby() is sorting by a column of Datetime

Upvotes: 0

Views: 928

Answers (3)

Hiệp L&#234;
Hiệp L&#234;

Reputation: 634

It could be either currentPage * pageSize is greater than allRows collection or pageSize is 0.

Upvotes: 0

Dan But
Dan But

Reputation: 658

Also you can use orderbydescending instead of orderby and then reverse

Upvotes: 1

Grant Winney
Grant Winney

Reputation: 66501

If currentPage * pageSize is higher than the number of elements in allRows, you'll get no records in pageOfRows.

Skip will not throw an exception if you inadvertently "skip" right past all your records. It'll just return an empty set.

From MSDN:

If source contains fewer than count elements, an empty IEnumerable is returned.

Place a breakpoint and check the number of records in pageOfRows and the result of currentPage * pageSize.

(Looking at your code, this is the most probable cause.)

Upvotes: 6

Related Questions