Instantiate empty IQueryable for use with Linq to sql

user2073077 picture user2073077 · Feb 21, 2013 · Viewed 72.7k times · Source

I need to be able to either have an optional parameter in a Linq query, or be able to assign the query to a var in something like an IF if that optional parameter needs to be removed from the query.

If I set the query var inside the IF statement then it tells me that the var doesn't exist in context when I try to loop through it.

if (whichGroup == "All")
        {
            var listOppLineData = (from o in db.opportunity_vws
                                   where o.fiscal_yr_and_qtr == qtr
                                   select o
                                  );
        }
        else
        {
            var listOppLineData = (from o in db.opportunity_vws
                                   where o.fiscal_yr_and_qtr == qtr && o.Group == whichGroup
                                   select o
                                  );
        }

        foreach (var data in listOppLineData)  //listOppLineData doesn't exist here
        {

I need to set the var before the IF statement I think, but I don't know what to set it to.

var listOppLineData = ""; // gives me 
Cannot implicitly convert type 'System.Linq.IQueryable<Forecast.Models.opportunity_vw>' to 'string'

IQueryable listOppLineData = new IQueryable(); //gives me
        Cannot create an instance of the abstract class or interface 'System.Linq.IQueryable'

Answer

Krishna picture Krishna · Apr 3, 2015

Try this. You can create a generic type with T or a specific type by replacing T with your type name.

IQueryable listOppLineData = Enumerable.Empty<T>().AsQueryable()