[英]How to: Use async methods with LINQ custom extension method
I have a 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());
}
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 但问题是我不想要ToList()我想要这样的东西
var spc = await context.pcs.DistinctBy(w => w.province).Select(w => new
{
abc = w
}).ToListAsync();
With Async. 使用Async。 But async is not found.
但是找不到异步。 How can I make my custom method distinctBy as such so I can also use it asynchronously?
如何使我的自定义方法distinctBy,所以我也可以异步使用它?
The ToListAsync()
extension method is extending an IQueryable<T>
, but your DistinctBy()
method is extending (and returning) an IEnumerable<T>
. ToListAsync()
扩展方法正在扩展IQueryable<T>
,但您的DistinctBy()
方法正在扩展(并返回)一个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). 显然,
ToListAsync()
不适用于IEnumerable<T>
因为它使用Linq-To-Objects(内存中)并且不能阻止(不涉及I / O)。
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
). 请注意,我还将
property
参数从Func<>
更改为Expression<Func<>>
以匹配Queryable.GroupBy
(并避免使用Enumerable.GroupBy
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.