c# - 如何: Use async methods with LINQ custom extension method

标签 c# .net entity-framework linq extension-methods

我有一个 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();

使用异步。但是找不到异步。我怎样才能让我的自定义方法 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

关于c# - 如何: Use async methods with LINQ custom extension method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41341042/

相关文章:

.net - Blazor 错误 : The SSL connection could not be established, 请参阅内部异常

c# - Entity Framework 不将元数据嵌入到 dll 中

c# - 使用 List<T>.Contains 方法为 LINQ 构建表达式树

c# - Entity Framework +验证注解

c# - 在大网格中路由路径的最佳方法是什么?

c# - 在 C# 中实现试用应用程序

c# - 现有连接被远程主机强行关闭

c# - System.Reflection 如何访问类成员数据/信息?

c# - 组合框下拉菜单出现在窗口下方

c# - 从 C# 向 azure 发送命令