Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Rows In A LINQ Result Without A Foreach Loop?

Tags:

c#

linq

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#?

like image 665
sooprise Avatar asked Jan 25 '26 21:01

sooprise


2 Answers

.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.

like image 173
Justin Niessner Avatar answered Jan 27 '26 11:01

Justin Niessner


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

like image 45
John Boker Avatar answered Jan 27 '26 10:01

John Boker