gpt4 book ai didi

c# - 如何避免将 iQueryable 转换为列表?

转载 作者:太空宇宙 更新时间:2023-11-03 21:19:57 26 4
gpt4 key购买 nike

我有以下(工作)代码:

 List<Location> allLocations = new List<Location>();
using (MyContext context = new MyContext())
{
Login currentLogin = GetCurrentLogin(context);
if (currentLogin != null)
{
foreach (var customer in currentLogin.Customers)
{
allLocations.AddRange(customer.Locations);
}
}
}
return allLocations.AsQueryable();

MyContext及其对象存在于 Entity Framework 中。 CustomersLocationsICollection<> -属性

此代码按预期工作,从用户的 Customers 返回所有位置

但是如您所见,我添加了实体 customer.LocationsList .

在该函数的末尾,我将生成的列表返回为 IQueryAble能够继续使用LinQ -对结果的表达。

由于性能原因,我想跳过 List<>-Step 并留在 IQueryAble

这可能吗?

最佳答案

如何在没有 foreach 循环的情况下使用 SelectMany 完成所有事情? ?这样你就可以将所有内容都保存为 IEnumerable:

using (MyContext context = new MyContext())
{
Login currentLogin = GetCurrentLogin(context);
if (currentLogin != null)
{
return currentLogin.Customers.SelectMany(c => c.Locations);
}
}

关于c# - 如何避免将 iQueryable 转换为列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31474869/

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