Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to: Use async methods with LINQ custom extension method

I have a LINQ custom extension method:

public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> items, Func<T, TKey> property)
{
    return items.GroupBy(property).Select(x => x.First());
}

And I am using it like this:

var spc = context.pcs.DistinctBy(w => w.province).Select(w => new
            {
                abc = w
            }).ToList();

But the problem is I don't want ToList() I want something like this

var spc = await context.pcs.DistinctBy(w => w.province).Select(w => new
             {
                 abc = w
             }).ToListAsync();

With Async. But async is not found. How can I make my custom method distinctBy as such so I can also use it asynchronously?

like image 969
user786 Avatar asked Dec 27 '16 07:12

user786


1 Answers

The ToListAsync() extension method is extending an IQueryable<T>, but your DistinctBy() method is extending (and returning) an IEnumerable<T>.

Obviously, ToListAsync() isn't available for IEnumerable<T> because it uses Linq-To-Objects (in-memory) and cannot potentially block (no I/O is involved).

Try this instead:

public static IQueryable<T> DistinctBy<T, TKey>(this IQueryable<T> items, Expression<Func<T, TKey>> property)
{
    return items.GroupBy(property).Select(x => x.First());
}

Notice that I also changed the property parameter from Func<> to Expression<Func<>> in order to match Queryable.GroupBy (and avoid Enumerable.GroupBy).

See MSDN

like image 100
haim770 Avatar answered Sep 27 '22 23:09

haim770