Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning empty IQueryable<>

I have this method that tries to get a list of things:

 private static IQueryable<Thing> GetThings(int thingsType)         {                 try                 {                     return from thing in entities.thing.Include("thingStuff")                            select thing;                 }                 catch (Exception exception)                 {                     return new EnumerableQuery<Thing>(?????);                 }             }          } 

I want to return an empty IQueryable if I can't for whatever reason get the query to run. I don't want to return NULL because that could break the calling code. Is it possible or am I going totally wrong about this?

like image 621
Otávio Décio Avatar asked Dec 13 '12 20:12

Otávio Décio


People also ask

What is IQueryable return?

IQueryable is executed. // // Returns: // A System.Type that represents the type of the element(s) that are returned when. // the expression tree associated with this object is executed.

What is IQueryable C#?

IQueryable<T> is a C# interface that lets you query different data sources. The type T specifies the type of the data source that you're querying. Under the hood, IQueryable uses expression trees that translate LINQ queries into the query language for the data provided.


2 Answers

These answers are good and do work, however I have always felt using Empty and not creating a new List is cleaner:

Enumerable.Empty<Thing>().AsQueryable(); 
like image 133
Chris Werner Avatar answered Oct 05 '22 23:10

Chris Werner


Try the following:

private static IQueryable<Thing> GetThings(int thingsType)     {             IQueryable<Thing> things = new List<Thing>().AsQueryable();             try             {                 things = from thing in entities.thing.Include("thingStuff")                        select thing;                  return things;             }             catch (Exception exception)             {                 return things;             }         } 
like image 37
mreyeros Avatar answered Oct 05 '22 22:10

mreyeros