Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get total results count before .Take() - but when using .Take()

Tags:

c#

linq

take

I am using .Take() to get a fixed number of results.

What is the best way to get the TotalCountBeforeTake (ie as if I didn't use the .Take())?

Can I get the TotalCountBeforeTake without running the query 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());
        }
like image 276
Ian G Avatar asked Aug 24 '13 09:08

Ian G


2 Answers

You want to query two things - the total number of items and a subset of items. So 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());
    }
like image 120
dtb Avatar answered Nov 03 '22 20:11

dtb


I don't know of a way to get the count without splitting this up (hopefully someone else does) but in your situation I'd 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());
}
like image 25
Paul D'Ambra Avatar answered Nov 03 '22 22:11

Paul D'Ambra