簡體   English   中英

如何:使用LINQ自定義擴展方法的異步方法

[英]How to: Use async methods with LINQ custom extension method

我有一個LINQ自定義擴展方法:

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

我這樣使用它:

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

但問題是我不想要ToList()我想要這樣的東西

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

使用Async。 但是找不到異步。 如何使我的自定義方法distinctBy,所以我也可以異步使用它?

ToListAsync()擴展方法正在擴展IQueryable<T> ,但您的DistinctBy()方法正在擴展(並返回)一個IEnumerable<T>

顯然, ToListAsync()不適用於IEnumerable<T>因為它使用Linq-To-Objects(內存中)並且不能阻止(不涉及I / O)。

試試這個:

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

請注意,我還將property參數從Func<>更改為Expression<Func<>>以匹配Queryable.GroupBy (並避免使用Enumerable.GroupBy )。

請參閱MSDN

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM