For every single LINQ query I've written, I've always used a foreach loop to go through the result. Now, I have a program where I want to get the first 50 rows of the result, do some calculations with those rows, then get the next 50 rows of the result etc.
What is the good standards way to do this using LINQ and C#?
.Skip().Take() is going to be the best method (as far as clarity goes) in this case. For example:
var results = db.Table.Select(); // Your query here
int rowCount = results.Count(); // Count rows once and store
for(int i = 0; i <= rowCount; i += 50)
{
var paged = results.Skip(i).Take(50);
// do the calculations with the groups of 50 here
}
It is worth noting that even though this seems more clear (you're taking groups of 50 from the results), each time you call Skip() and Take() there's a chance that the collection has to be enumerated over again...which is actually less efficient than simply using foreach to enumerate over the results a single time.
You could use a group by ie:
data.Select((item, index) => new {item, index}).GroupBy(g => g.index / 50)
then you'd do your operation on each group.
similar to this: How to use Linq to group every N number of rows
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With