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

如何将同一个var类型变量赋值给不同的LINQ to SQL结果集?

解决方案

你遇到的问题核心是var为隐式类型推断语法,声明时必须确定具体类型,无法延迟到后续赋值时推断,且object类型不支持LINQ扩展方法调用,你只需要显式声明变量为适配你返回结果的泛型接口类型即可实现需求。

具体实现步骤

  1. 声明变量时显式指定类型为IQueryable<CustomClass>,同时初始化空查询作为默认值,避免后续空引用异常:
IQueryable<CustomClass> resultSet = Enumerable.Empty<CustomClass>().AsQueryable();
  1. 按条件赋值对应查询即可,所有查询返回的都是CustomClass类型的可查询对象,类型匹配可以直接赋值:
if(somecondition)
{
   resultSet = from t1 in table1 where t1.id == 1 select new CustomClass {Id = t1.id, name = "test1"};
}
if(anotherCondition)
{
   resultSet = from t2 in table2 where t2.id == 1 select new CustomClass {Id = t2.id, name = "test2"};
}
  1. 后续LINQ操作可以正常执行:
resultSet = resultSet.OrderByDescending(d => d.Id).ToArray();
var count = resultSet.Count();

可选拓展:累加多个查询结果

如果需要同时保留多个条件命中的所有查询结果,而不是后赋值的覆盖之前的,可以使用Union方法拼接查询:

if(somecondition)
{
   resultSet = resultSet.Union(from t1 in table1 where t1.id == 1 select new CustomClass {Id = t1.id, name = "test1"});
}
if(anotherCondition)
{
   resultSet = resultSet.Union(from t2 in table2 where t2.id == 1 select new CustomClass {Id = t2.id, name = "test2"});
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 22:54:03