You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将未知类型的IQueryable结果存储到列表中?

存储LINQ匿名类型查询的正确类型

针对你要存储这类LINQ查询的需求,有几种可行的类型选择,各有优劣:

1. 非泛型IQueryable集合

直接使用List<IQueryable>来存储,这是最直接的方式,因为所有泛型IQueryable<T>都实现了非泛型的IQueryable接口:

var queries = new List<IQueryable>();
for(int i = 0; i<5;i++)
{
    var query = from p in DBContext.Products
                from pp in DBContext.Pricing
                select new { p, pp };
    queries.Add(query);
}
  • 缺点:取出查询使用时,会丢失编译时类型检查,只能通过dynamic或反射来访问匿名类型的属性,无法获得类型安全保障。

2. 自定义实体类+泛型IQueryable<T>

这是最优方案,通过定义一个具体的类替代匿名类型,既能保留类型安全,又能正常存储查询:
首先创建对应的数据类:

public class ProductPricingPair
{
    public Product Product { get; set; }
    public Pricing Pricing { get; set; }
}

然后用List<IQueryable<ProductPricingPair>>存储查询:

var queries = new List<IQueryable<ProductPricingPair>>();
for(int i = 0; i<5;i++)
{
    var query = from p in DBContext.Products
                from pp in DBContext.Pricing
                select new ProductPricingPair { Product = p, Pricing = pp };
    queries.Add(query);
}
  • 优点:完全保留编译时类型检查,使用查询结果时无需额外转换,代码可读性和安全性都更高。

3. List<IQueryable<object>>

通过Cast<object>将匿名类型查询转为IQueryable<object>后存储:

var queries = new List<IQueryable<object>>();
for(int i = 0; i<5;i++)
{
    var query = from p in DBContext.Products
                from pp in DBContext.Pricing
                select new { p, pp };
    queries.Add(query.Cast<object>());
}
  • 缺点:同样丢失类型安全,取出后需要转换为dynamic或通过反射访问属性,仅比非泛型IQueryable多一层类型约束,实用性不强。

内容的提问来源于stack exchange,提问作者AliK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 18:05:27