gpt4 book ai didi

c# - 合并 Linq 查询

转载 作者:行者123 更新时间:2023-11-30 17:15:45 24 4
gpt4 key购买 nike

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

我正在使用(阅读学习)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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com