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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With