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

标签 c# linq entity-framework iqueryable

我有以下(工作)代码:

 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/

相关文章:

c# - 为什么我不能在带有 System.Net.Http 引用的解决方案中使用 System.Net.Http 包?

c# - 对另一个 LINQ 查询的 LINQ 查询

c# - Entity Framework - 为集合中的成员加载特定的导航属性

c# - 如何使用 LocalPrintServer 定位特定打印机?

c# - 在 Windows Phone 8 App 中播放音效

c# - WCF 服务不喜欢单引号

c# - 是否可以在 LinQ 中的 where 子句中使用条件?

.net - 如何使用 LINQ to XML 按属性查找 XML 元素?

c# - 使用 LINQ 通过单个查询获取外键表

c# - Entity Framework |错误 : InvalidCastException: The field of type System. Int32 必须是字符串、数组或 ICollection 类型