0

I came across this pretty little piece of code here:

 List<DataTable> result = DTHead.AsEnumerable()
            .GroupBy(row => row.Field<int>("MIVID"))
            .Select(g => g.CopyToDataTable())
            .ToList();

It creates a List of DataTable's based on the value of a particular field.

Is it possible to tweak this code to instead create a List of DataTables based on the number of records? For example, if I have 18 records, I would want that broken into 2 DataTables with 10 rows each (the last two rows of the second table would be empty). If I have 35 records, I end up with 4 DataTable's, the last 5 rows empty on table 4.

Thanks!

Community
  • 1
  • 1
brainbolt
  • 616
  • 1
  • 10
  • 24

1 Answers1

0

This is like a standard paging mechanism:

var result = DTHead.AsEnumerable();

int pageSize = 10;
int pages = result.Count / pageSize + 1;
for (int i = 0; i < pages; i++)
{
    var page = result.Skip(i * pageSize).Take(pageSize).Select (t => t.Name)
                     .CopyToDataTable();
}

Of course within the loop you'd have to do something meaningful with the page variable.

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
  • So there isn't a way to do it through the query itself? You have to do a loop like this? – brainbolt Dec 24 '12 at 22:38
  • I wouldn't know how. It is quite different than grouping. Try to think how it could be done in sql. Something with ROW_NUMBER? But how? And then the problem would be how to do it with linq (no ROW_NUMBER function in EF!). BTW I saw that I inadvertently copied `CopyToDataTable` in the main query. – Gert Arnold Dec 24 '12 at 23:24
  • In that case, given that I'm starting with a SQL query, and ultimately want to end up with a group of collections that will be bound to either a series of `GridView`'s or `Repeater`'s, do you think your suggestion would be the best way to go, or is there something else you recommend? I'm not married to LINQ, I was just intrigued by the original code sample because it seems elegant. – brainbolt Dec 25 '12 at 09:23
  • Again, I don't see alternatives. Similar things have been ventured before, e.g. http://stackoverflow.com/q/11542406/861716. It always boils down to Skip/Take. – Gert Arnold Dec 25 '12 at 09:32