问题描述:

I have a simple entity framework query.

It uses grouping:

source.GroupBy(x => x.Key)

.Select(x => x.Count(z => z.IsDefaultValue == false) > 0

? x.FirstOrDefault(z => z.IsDefaultValue == false)

: x.FirstOrDefault()

);

Execution plan for it looks like this:

Then I change the query:

source.GroupBy(x => x.Key)

.Select(x => x.Any(z => z.IsDefaultValue == false)

? x.FirstOrDefault(z => z.IsDefaultValue == false)

: x.FirstOrDefault()

);

Now I use Any instead of Count.

It's plan looks like this:

My question is: what query should I use?

What query is more efficient?

I don't understand anything about execution plans :(

What important information do you see on these execution plans?

EDIT: Please drag pictures in a new tab, it will be more readable.

网友答案:

My question is: what query should I use? What query is more efficient?

To find the answer to that, I would simply take both of the SQL queries that have been generated (you can see the full query in the plan's xml) and run them in one SQL Server Management Studio query window together, with the "Include actual execution plan" option on.

The "Query cost (relative to the batch)" on the resulting plan will then tell you which one is more efficient on your actual schema/data.

What about EF's Any() vs Count() > 0 ? Which is more efficient?

In general if you just want to know if any of the "things" match your criteria, then it's often suggested you use Any() instead of Count() > 0 and let LINQ worry about constructing the most efficient way. In this use case I would just check the SQL and see.

See answers like this

For just IEnumerable<T>, then Any() will generally be quicker, as it only has to look at one iteration.

相关阅读:
Top