我有认识的IQueryable&LT的问题; T> [英] I'm having problems understanding IQueryable<T>

查看:104
本文介绍了我有认识的IQueryable&LT的问题; T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想了解的IQueryable< T> 。该教程我阅读建议使用它,但真的不知道为什么。在code简单地返回使用LINQ to SQL中的值。我这样做很多次在过去,但没有使用的IQueryable< T>

为什么我的函数返回多个值使用它?

下面是我的code:

 公开的IQueryable<项目> GetItems()
    {
        从db.Items物品返还
               其中,item.IsActive == TRUE
               排序依据item.ItemNumber
               选择项目;
    }


解决方案

IQueryable的再presents查询作为一个前pression树,而无需在服务器上的评测吧。这让你实际生成的SQL之前指定进一步的处理。

在上述情况下,这意味着你可以做的东西与调用GetItems()的结果,并有原始查询并派作为一个单一的查询多余的东西:

  VAR recentItems =从GetItems项目()
                  其中,item.Timestamp> somedate
                  选择项目;的foreach(在recentItems VAR项)
{
    //做一些事情的积极最近的项目。
}

,直到我们尝试使用该结果在foreach循环没有被发送到服务器。在这一点上,LINQ到SQL供应商评估整个前pression,包括里面的产生的位GetItems()后指定的位数,并发出一个选择是主动和最近的所有项目SQL语句。

要澄清一个技术性的的IQueryable< T> 的IEnumerable< T> ,和它的供应商单位计算当您试图调用的GetEnumerator()方法就可以了最终的SQL。您可以通过在的foreach 语句中使用它调用它,或含蓄做到这一点明确。此外,扩展方法,如 ToArray的()会做这些中的一个内部,从而产生同样的效果。

So I'm trying to understand IQueryable<T>. A tutorial I'm reading suggests using it but not really sure why. The code simply returns some values using LINQ to SQL. I've done this plenty of times in the past, but not using IQueryable<T>

Why use it with my functions that return more than 1 value?

Here's my code:

public IQueryable<Items> GetItems()
    {
        return from item in db.Items
               where item.IsActive == true
               orderby item.ItemNumber
               select item;
    }

解决方案

IQueryable represents the query as an expression tree without evaluating it on the server. This lets you specify further processing before actually generating SQL.

In the above case, this means that you can do stuff with the result of calling GetItems(), and have the original query and the extra stuff sent as a single query:

var recentItems = from item in GetItems()
                  where item.Timestamp > somedate
                  select item;

foreach (var item in recentItems)
{
    // Do something with an active recent item.
}

Nothing is sent to the server until we try to consume the result in the foreach loop. At that point, the LINQ-to-SQL provider assesses the entire expression, including the bits generated inside GetItems() and the bits specified after, and emits a single SQL statement that selects all items that are both active and recent.

To clarify a technicality, the IQueryable<T> is an IEnumerable<T>, and its provider computes the final SQL when you try to invoke the GetEnumerator() method on it. You can either do this explicitly by calling it, or implicitly by using it in a foreach statement. Also, extension methods like ToArray() will do one of these internally, thus producing the same effect.

这篇关于我有认识的IQueryable&LT的问题; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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