globetrotter
globetrotter

Reputation: 1047

c# async when returning LINQ

I've just realised that this code:

    public async Task<List<Review>> GetTitleReviews(int titleID)
    {
        using (var context = new exampleEntities())
        {
            return await context.Reviews.Where(x => x.Title_Id == titleID).ToList();        
        }
    }

...will not work as async methods cannot await LINQ expressions. I've did some searches but only managed to find some overcomplicated solutions.

How should functions which return LINQ expressions be converted to async versions?

Upvotes: 5

Views: 8964

Answers (3)

&#194;ngelo Polotto
&#194;ngelo Polotto

Reputation: 9531

I solved this problem creating an Enumerable extension. That was needed for me because Xamarin Forms don't have Linq ToListAsync support. This is my extension:

public static class EnumerableExtension
{
    public static Task<List<T>> ToListAsync<T>(this IEnumerable<T> enumerable)
    {
        return Task.Run(enumerable.ToList);
    }
}

Upvotes: 0

sa_ddam213
sa_ddam213

Reputation: 43596

Add the System.Data.Entity namespace and take advantage of the Async extension methods

In this case ToListAsync should do the trick

using System.Data.Entity;

public async Task<List<Review>> GetTitleReviews(int titleID)
{
    using (var context = new exampleEntities())
    {
        return await context.Reviews.Where(x => x.Title_Id == titleID).ToListAsync();        
    }
}

Upvotes: 13

Peter Duniho
Peter Duniho

Reputation: 70661

Technically, that method doesn't return a lambda. It returns a List<Review>.

It's true what you posted won't compile. But this would:

public async Task<List<Review>> GetTitleReviews(int titleID)
{
    using (var context = new exampleEntities())
    {
        return await Task.Run(() => context.Reviews.Where(x => x.Title_Id == titleID).ToList());
    }
}

If that doesn't answer your question, maybe you can be more clear about exactly what you're trying to accomplish and why the above doesn't do it.

Upvotes: 6

Related Questions