我有一个场景:
例如
我有这个
var resultSet;
现在我需要将这个赋值给多个LINQ-SQL结果,比如
if(somecondition)
{
resultSet= (from t1 in table1 where t1.id= 1 select new CustomClass {name='test1'})
}
if(anotherCondition)
{
resultSet = (from t2 in table2 where t2.id= 1 select new CustomClass {name='test2'})
}
resultSet= resultSet.OrderByDescending(d => d.Id)
.ToArray()
var count= resultSet.Count();
但问题是,如果我全局地使用resultSet
,那么它就不能工作,如果我分配NULL
,它就不能工作,因为它不能被分配给var resultSet= new Object()
,如果我给它分配像var resultSet= new Object()
这样的东西,那么函数,如.count(), orderby
等就不能工作。
我该怎么办?
我需要使用相同的变量,用于不同的dbcontext
表,但具有相同的类。
发布于 2021-09-08 00:13:46
您需要将resultSet
定义为IEnumerable<CustomClass>
IEnumerable<CustomClass> resultSet = null;// Must be assigned to something
if(somecondition)
{
resultSet= (from t1 in table1 where t1.id= 1 select new CustomClass {name='test1'})
}
if(anotherCondition)
{
resultSet = (from t2 in table2 where t2.id= 1 select new CustomClass {name='test2'})
}
resultSet= resultSet.OrderByDescending(d => d.Id)
.ToArray()
var count= resultSet.Count();
您也可以选择使用IQueryable<CustomeClass>
,但是您会想要删除ToArray()
部件。
发布于 2021-09-08 00:23:18
听起来您想要的是将结果集的作用域放在填充它的代码之外:
例如,
public class SomeClass
{
public IEnumerable<CustomClass> ResultSet { get; private set; } = new List<CustomClass>();
//Pseudo: values and conditions are just indicative of logic.
public void SomeMethod(someValue, someOtherValue)
{
IQueryable<CustomClass> resultSet = null;
if(somecondition)
resultSet = (from t1 in table1 where t1.id= 1 select new CustomClass {name='test1'});
else if(anotherCondition)
resultSet = (from t2 in table2 where t2.id= 1 select new CustomClass {name='test2'});
else
throw new ArgumentException("Invalid combination of conditions.");
ResultSet = resultSet.OrderByDescending(d => d.Id)
.ToArray();
var count= resultSet.Count;
}
https://stackoverflow.com/questions/69099227
复制相似问题