Home > Enterprise >  How to assign the same var type variable to different linq to sql result sets?
How to assign the same var type variable to different linq to sql result sets?

Time:09-17

I have a scenario:

For example

I have this

var resultSet;

Now this I need to assign to multiple LINQ-SQL result like

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();

but issue is that if i take resultSet globally then it doesn't work and if I assign NULL it won't work since it cannot be assigned to null and if i assign it something like var resultSet= new Object() then functions i.e. .count(), orderby etc. won't work.

what should I do?

I need to use the same variable and for different dbcontext tables but with same class.

CodePudding user response:

You would need to define resultSet as 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();

You could also choose to use IQueryable<CustomeClass> but then you'd want to remove the ToArray() part.

CodePudding user response:

What is sounds like what you want is to scope the result set outside of the code that populates it:

for example,

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;

}
  • Related