我误解了 LINQ to SQL .AsEnumerable() 吗? [英] Am I misunderstanding LINQ to SQL .AsEnumerable()?

查看:26
本文介绍了我误解了 LINQ to SQL .AsEnumerable() 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个代码:

var query = db.Table
              .Where(t => SomeCondition(t))
              .AsEnumerable();

int recordCount = query.Count();
int totalSomeNumber = query.Sum();
decimal average = query.Average();

假设 query 需要很长时间才能运行.我需要获取记录计数、返回的 SomeNumber 总数,并在最后取平均值.根据我的阅读,我认为 .AsEnumerable() 将使用 LINQ-to-SQL 执行查询,然后将 LINQ-to-Objects 用于 Count, SumAverage.相反,当我在 LINQPad 中执行此操作时,我看到相同的查询运行了 3 次.如果我用 .ToList() 替换 .AsEnumerable(),它只会被查询一次.

Assume query takes a very long time to run. I need to get the record count, total SomeNumber's returned, and take an average at the end. I thought based on my reading that .AsEnumerable() would execute the query using LINQ-to-SQL, then use LINQ-to-Objects for the Count, Sum, and Average. Instead, when I do this in LINQPad, I see the same query is run three times. If I replace .AsEnumerable() with .ToList(), it only gets queried once.

我是否遗漏了一些关于 AsEnumerable 是/做什么的信息?

Am I missing something about what AsEnumerable is/does?

推荐答案

调用 AsEnumerable() 不执行查询,枚举它执行.

Calling AsEnumerable() does not execute the query, enumerating it does.

IQueryable 是允许 LINQ to SQL 发挥其魔力的接口.IQueryable 实现了 IEnumerable,因此当您调用 AsEnumerable() 时,您正在更改从那里调用的扩展方法,即从 IQueryable-methods 到 IEnumerable-methods(即在这种特殊情况下从 LINQ to SQL 更改为 LINQ to Objects).但是您没有执行实际的查询,只是改变了如何将要完整地执行.

IQueryable is the interface that allows LINQ to SQL to perform its magic. IQueryable implements IEnumerable so when you call AsEnumerable(), you are changing the extension-methods being called from there on, ie from the IQueryable-methods to the IEnumerable-methods (ie changing from LINQ to SQL to LINQ to Objects in this particular case). But you are not executing the actual query, just changing how it is going to be executed in its entirety.

要强制执行查询,您必须调用 ToList().

To force query execution, you must call ToList().

这篇关于我误解了 LINQ to SQL .AsEnumerable() 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆