如何将同一个var类型变量赋值给不同的LINQ to SQL结果集?
解决方案
你遇到的问题核心是var为隐式类型推断语法,声明时必须确定具体类型,无法延迟到后续赋值时推断,且object类型不支持LINQ扩展方法调用,你只需要显式声明变量为适配你返回结果的泛型接口类型即可实现需求。
具体实现步骤
- 声明变量时显式指定类型为
IQueryable<CustomClass>,同时初始化空查询作为默认值,避免后续空引用异常:
IQueryable<CustomClass> resultSet = Enumerable.Empty<CustomClass>().AsQueryable();
- 按条件赋值对应查询即可,所有查询返回的都是
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"}; }
- 后续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
相关产品推荐
相关产品推荐

