简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM