linq如何实际执行代码以从数据源检索数据?

Cru*_*ces 6 c# linq

我将很快开始研究xamarin,并将把很多代码从android studio的java转移到c#.

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

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

例如,目前会发生的事情就是沿着这些方向发展

List<Customer> customers = (new CustomerDAO()).get_all()
Run Code Online (Sandbox Code Playgroud)

或者,如果我有条件

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

现在让我们假设我已经将类转移到了c#,我希望做一些类似于第二种情况的方法.

所以我可能会写下以下内容:

var customers = from customer 
    in (new CustomerDAO()).get_all() 
    where customer.code.equals("code1")
    select customer
Run Code Online (Sandbox Code Playgroud)

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

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

Select * from Customers where code = 'code1'
Run Code Online (Sandbox Code Playgroud)

并将结果加载到对象?

提前感谢您提供的任何帮助

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

Yuv*_*kov 4

如果我对客户进行多次访问(假设我稍后使用 4 个 foreach 循环) get_all 方法是否会被调用 4 次?或者结果是否存储在第一次执行时?

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

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

然后,现在您将使用内存中的数据,List<Customer>而无需再次执行查询。

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

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

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

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

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