c# - 如何在 .Take() 之前获得总结果计数 - 但在使用 .Take() 时

标签 c# linq take

我正在使用 .Take() 来获取固定数量的结果。

获取 TotalCountBeforeTake 的最佳方法是什么(即好像我没有使用 .Take())?

我可以在不运行查询两次的情况下获得 TotalCountBeforeTake 吗?

        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());
        }

最佳答案

您想查询两件事 - 项目的总数和项目的子集。所以你需要运行两个查询:

    // 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());
    }

关于c# - 如何在 .Take() 之前获得总结果计数 - 但在使用 .Take() 时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18416873/

相关文章:

linq - RavenDB OrderByDescending 和 Take - 错误结果

c# - 如何在使用嵌套属性计算值的只读属性上触发 INotifyPropertyChanged

c# - 不执行 linq 导致内存分配 C#

linq - 使用 LINQ 在子查询中高级多重联接

c# - 找到 x 项后中止 linq 查询?

scala - Spark : Difference between collect(), take() 和 show() 转换为 DF 后的输出

c# - Numpy.NET 获取值

c# - unity Recttransform 包含点

c# - 使用 DX11 渲染文本

c# - 从 IEnumerable<Dictionary<string, object>> 获取键和值