LINQ计数...最佳方法[英] LINQ Count .. best method

本文是小编为大家收集整理的关于LINQ计数...最佳方法的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我的公司刚刚开始使用 LINQ,但我仍然对 LINQ 命令和 SQL 的抽象性(如果这是一个词)有点麻烦,我的问题是

  Dim query = (From o In data.Addresses _
                    Select o.Name).Count

在我的脑海中,SQL 正在返回所有行,并且对 IQueryable 结果中的行数进行计数,所以我会更好

    Dim lstring = Aggregate o In data.Addresses _
    Into Count()

或者我是否过度思考 LINQ 的工作方式?在家里使用 VB Express,所以我看不到发送到数据库的实际 SQL(我认为),因为我无权访问 SQL 分析器

推荐答案

如前所述,这些在功能上是等效的,只是使用查询语法.

正如我在评论中提到的,如果您将以下内容评估为 LINQPad 中的 VB 语句:

Dim lstring = Aggregate o In Test _
    Into Count()

您可以在生成的 SQL 输出窗口中看到:

SELECT COUNT(*) AS [value]
FROM [Test] AS [t0]

这与评估的以下 VB LINQ 表达式相同:

(From o In Test_
    Select o.Symbol).Count

你得到完全相同的结果.

本文地址:https://www.itbaoku.cn/post/1556830.html

问题描述

My company has just started using LINQ and I still am having a little trouble with the abstractness (if thats a word) of the LINQ command and the SQL, my question is

  Dim query = (From o In data.Addresses _
                    Select o.Name).Count

In the above in my mind, the SQL is returning all rows and the does a count on the number rows in the IQueryable result, so I would be better with

    Dim lstring = Aggregate o In data.Addresses _
    Into Count()

Or am I over thinking the way LINQ works ? Using VB Express at home so I can't see the actual SQL that is being sent to the database (I think) as I don't have access to the SQL profiler

推荐答案

As mentioned, these are functionally equivalent, one just uses query syntax.

As mentioned in my comment, if you evaluate the following as a VB Statement(s) in LINQPad:

Dim lstring = Aggregate o In Test _
    Into Count()

You get this in the generated SQL output window:

SELECT COUNT(*) AS [value]
FROM [Test] AS [t0]

Which is the same as the following VB LINQ expression as evaluated:

(From o In Test_
    Select o.Symbol).Count

You get the exact same result.