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

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

问题描述

考虑这个code:

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

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

假设查询需要很长的时间来运行。我需要记录数,总 SomeNumber 的返回,取一个平均值,在年底。我以为根据我读了 .AsEnumerable()将执行使用LINQ到SQL,然后使用LINQ到对象的查询计数总和平均。相反,当我这样做的LINQPad,我看到了同样的查询运行三次。如果我更换 .AsEnumerable() .ToList(),它只能被查询一次。

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 does not execute the query, enumerating it does.

的IQueryable 是允许的LINQ to SQL 来执行其神奇的接口。 的IQueryable 工具的IEnumerable 所以,当你调用 AsEnumerable(),您正在起变化伸展方法从那里被调用,即的IQueryable - 方法的的IEnumerable - 方法(即从的LINQ to SQL 在这种特殊情况下更改为 LINQ到对象)。但是你的不可以执行实际的查询,只是改变如何它是将其全部执行。

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天全站免登陆