c# - 合并 Linq 查询

标签 c# linq linq-to-sql ninject

有人能解释一下当我执行这个查询时会发生什么吗

我正在使用(阅读学习)ninject 并有以下代码

public interface IProducts
{
    IQueryable<Product> Products { get; }

   //some functions

}

我有以下实现 IProducts 接口(interface)的类“Product”

public class Product
{
    public string Name { get; set; }
    public string Price { get; set; }

    public IQueryable<Product> Products
    {
        get
        {
            using(/*Connect to dtabase*/)
            {
                var products = from p in db.Products
                               select p;
            }
        }
    }
}

现在我已经添加了

ninjectKernel.Bind<IProducts>().To<Product>();

我想知道如果我添加另一个 Linq 查询会发生什么,例如 where product.Name == Something

例如

public class ProductController : Controller
{
    private IProducs repository;

    public ProductController(IProducts products)
    {
         repository = products;
    }

    public ViewResult Find(string productName)
    {
          var product = from p in repository
                         where p.Name == productName
                         select p;
     }
}

据我所知,Linq 查询只会在我循环遍历数据时执行,所以我想知道这两个 Linq 查询是否会合并为一个。

例如

from p in db.Products
where p.Name == Something
select p;

如果我做对了,有人可以确认我吗

最佳答案

编译器将有效地将您的声明性 LINQ 语句转换为方法调用。 (我说有效是因为它真的取决于编译器内部,方法转换是否真的发生,或者它是否直接“捷径”到 IL - 在这种情况下,这对我们来说并不重要。)

即:-

from p in db.Products
    select p;

代表

db.Products.Select(p => p);

from p in repository.Products    // .Products is missing in your code
    where p.Name == productName
    select p

代表

repository.Products.Where(p => p.Name == productName);

现在,由于延迟执行,当我们枚举我们的最终值(“循环数据”)时,将有效地执行以下内容:-

db.Products.Select(x => x).Where(p => p.Name == productName);

接下来就是IQueryable<T>的具体实现了( db.Products ) 将其翻译成任何合适的。对于 Linq2SQL 提供程序,这将类似于:-

SELECT
    P.Name, P.Foo, P.Bar, ...
FROM
    Product P
WHERE
    P.Name = "the name you specify"

所以你看,由于延迟执行,对数据库的单个查询的转换是为你完成的。您无需采取任何特殊措施即可实现这一目标。

关于c# - 合并 Linq 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7778692/

相关文章:

c# - 嵌套查询的 StackOverflowException,小项目计数

c# - 使用Newtonsoft如何避免 ":"后的tailing space空间

c# - Linq 避免两次调用函数

c# - 将两个查询的左外连接转换为 LINQ

linq - 如何使用 FLinq 在 F# 中进行外连接?

c# - 下面的空条件运算符有什么问题?

c# - 使用接口(interface)有什么好处?

c# - 如何在 linq 中为两个不相等的列表保留外连接

c# - 计算 linq Entity Framework 中的子匹配项

c# - Linq to sql - 数据库不会更新