locked
Convert from IEnumerable to IQueryable RRS feed

  • Question

  • I'm writing access methods that query data from a database that return an IQueryable object. If something goes wrong, though, I don't want to return null, but rather an empty list. I thought I had the following working:

    IQueryable<MyType> GetAllThings()
    {
       IQueryable<MyType> returnList = null;

       try
       {
          // Get Things from the database
       }
       catch (Exception exception)
       {
          // Handle exceptions
       }

       if (returnList == null)
          returnList = new List<MyType>() as IQueryable<MyType>;

       return returnList
    }

    But it turns out that "List<MyType>() is IQueryable<MyType>" is false, so returnList stays null.

    Is there a way to convert a list to an IQueryable? Or even just a way to create an empty IQueryable object?

    Thanks!
    Saturday, August 2, 2008 1:32 PM

Answers

  • You can call .AsQueryable() on an IEnumerable<T> sequence and it will return IQueryable<T>.

    But I would seriously question why you'd want to do this. Returning an empty list in case of an exception is almost always a bad pattern - if an unknown exception is thrown, you really want to let that exception bubble up.

    Joe
    Saturday, August 2, 2008 1:48 PM

All replies

  • You can call .AsQueryable() on an IEnumerable<T> sequence and it will return IQueryable<T>.

    But I would seriously question why you'd want to do this. Returning an empty list in case of an exception is almost always a bad pattern - if an unknown exception is thrown, you really want to let that exception bubble up.

    Joe
    Saturday, August 2, 2008 1:48 PM
  • Thanks, Joe.

    It's not always in that case, it was just the example case. Often I call these methods in a foreach loop and returning null causes an exception.

    I do use the above pattern for my generated code, but in that case I allow the user to define a delegate for exceptions, meaning they can trap, log, and/or throw the exception as they please. I just don't want their code to break if they do with to keep the exception suppressed, which is why I wanted the empty list.

    Thanks again!
    Saturday, August 2, 2008 2:26 PM