gpt4 book ai didi

c# - linq实际上是如何执行代码从数据源中获取数据的呢?

转载 作者:太空狗 更新时间:2023-10-29 21:43:35 25 4
gpt4 key购买 nike

我很快就会开始研究 xamarin,并将大量代码从 android studio 的 java 转移到 c#。

在 java 中,我使用自定义类,给定参数条件等,将它们转换为 SQL 语句,然后将结果加载到项目模型中的对象

我不确定 linq 是否是过滤此类数据的更好选择。

例如,当前会发生的事情是这样的

List<Customer> customers = (new CustomerDAO()).get_all()

或者如果我有条件

List<Customer> customers = (new CustomerDAO()).get(new Condition(CustomerDAO.Code, equals, "code1")

现在让我们假设我已经将类转移到 c# 并且我希望做一些类似于第二种情况的事情。

所以我可能会按照以下思路写一些东西:

var customers = from customer 
in (new CustomerDAO()).get_all()
where customer.code.equals("code1")
select customer

我知道查询只会在我实际尝试访问客户时执行,但是如果我有多个客户访问权限(假设我稍后使用 4 个 foreach 循环),get_all 方法会被调用 4 次吗?还是在第一次执行时存储结果?

仅保留 get_all() 方法并使用 linq 过滤结果是否更有效(时间方面因为内存方面可能不是)?或者使用我现有的设置,它实际上执行了

Select * from Customers where code = 'code1'

并将结果加载到一个对象中?

在此先感谢您提供的任何帮助

编辑:是的,我确实知道有 sqlite.net,它几乎可以做我的 daos 所做的事情,但可能更好,并且在某些时候我可能会转换我所有的对象来使用它,我只需要知道是为了知道

最佳答案

if I have multiple accesses to customers ( let us say that I use 4 foreach loops later on) will the get_all method be called 4 times? or are the results stored at the first execution?

每次您枚举枚举器(在您的示例中使用 foreach)时,查询将重新执行,除非您将具体化结果存储在某处。例如,如果您在第一个查询中执行以下操作:

var customerSource = new CustomerDAO();
List<Customer> customerSource.Where(customer => customer.Code.Equals("code1")).ToList();

那么现在您将使用内存中的 List<Customer>无需再次执行查询。

相反,如果每次你都这样做:

var filteredCustomers = customerSource.Where(customer => customer.Code.Equals("code1"))
foreach (var customer in filteredCustomers)
{
// Do stuff
}

然后对于每个枚举,您将再次执行上述查询。

Also is it more efficient (time wise because memory wise it is probably not) to just keep the get_all() method and use linq to filter the results? Or use my existing setup which in effect executes

这实际上取决于您的用例。假设您正在使用 LINQ to EF,并且客户表有一百万行,您真的想要将所有行都放入内存中,然后过滤掉它们以使用数据子集吗?完全过滤查询通常会更好。

关于c# - linq实际上是如何执行代码从数据源中获取数据的呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36823424/

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