How to get the total number of results before .Take () - but when using .Take ()

I use .Take () to get a fixed amount of results.

What is the best way to get TotalCountBeforeTake (i.e. as if I hadn't used .Take ())?

Is it possible to get TotalCountBeforeTake without executing the request twice?

  var Results = (from results in db.FindWords(term) orderby results.word select results.word).Take(100); //just to get the total record count int TotalCountBeforeTake = (from results in db.FindWords(term) select results.word).Count(); // only showing 100 out of TotalCountBeforeTake results, // but in order to know the TotalCountBeforeTake I had to run the query twice. foreach (var result in Results) { Console.Write(result.ToString()); } 
+4
source share
3 answers

You want to request two things - the total number of elements and a subset of the elements. Therefore, you need to run two queries:

  // Define queries var query1 = from results in db.FindWords(term) orderby results.word select results.word; var query2 = query1.Take(100); // Run queries int totalCountBeforeTake = query1.Count(); foreach (var result in query2) { Console.Write(result.ToString()); } 
+7
source

I don’t know how to get an invoice without breaking it (I hope someone else does it), but in your situation I would suggest:

 //first get the records var query = (from results in db.FindWords(term) orderby results.word select results.word).ToList(); //get the total record count int TotalCountBeforeTake = query.Count(); // only showing 100 out of results, foreach (var result in query.Take(100)) { Console.Write(result.ToString()); } 
+1
source

IEnumerables and LINQ are used to create the selection chain. Before you start iterating, nothing is done (other than creating a selection chain).

This seems magical because it dramatically improves performance, because it takes several iterations of the list to achieve the same with lists.

But when you begin to repeat the enumeration several times, you buy LINQ elegance with several operations, which reduces the efficiency of your work to zero or lower.

In other words: convert the linq expression to an array and continue.

  var Results = (from results in db.FindWords(term) orderby results.word select results.word).Take(100).ToArray(); 

Now you can count iterations without losing performance.

-3
source

Source: https://habr.com/ru/post/1498708/


All Articles