我有一个LINQ自定义扩展方法:
public class AppLocationServices extends Service implements IAsyncTask{
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(final Intent intent, final int flags,
final int startId) {
if(getBaseContext()!=null){
SessionManagement sessionManagement = new SessionManagement(getBaseContext());
if(sessionManagement.isLoggedIn() && !Util.IsOwner(Util.GetLocalStorage(sessionManagement))){
if(getBaseContext()!=null && intent.getExtras()!=null && intent.getExtras().getString("ClassName").equalsIgnoreCase(ReceiverLocationAlarm.class.getName())){
Util.SetOnReceiverLocationIntent(getBaseContext());
LocationProvider mLocationProvider = new LocationProvider(getBaseContext());
mLocationProvider.connect();
}
else if(getBaseContext()!=null && intent.getExtras()!=null && intent.getExtras().getString("ClassName").equalsIgnoreCase(SenderLocationAlarm.class.getName())){
Util.SetOnSenderLocationIntent(getBaseContext());
DataBaseHelper dataBaseHelper = new DataBaseHelper(getBaseContext());
if(dataBaseHelper.getFromGpsItem().size()>0)
new SendLocationToServer(getBaseContext(),AppLocationServices.this).execute();
}
}else {
LocationProvider mLocationProvider = new LocationProvider(getBaseContext());
mLocationProvider.disconnect();
Util.StopOnReceiverLocationIntent(getContext());
Util.StopOnSendLocationIntent(getContext());
stopSelf();
}
}
return Service.START_REDELIVER_INTENT;
}
@Override
public Context getContext() {
return getBaseContext();
}
@Override
public Fragment getFragment() {
return null;
}
@Override
public void OnPreExecute() {
}
@Override
public void OnPostExecute(String URL, JSONObject jsonObject) {
}
@Override
public void OnErrorMessage(String Message) {
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
我正在使用它:
public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> items, Func<T, TKey> property)
{
return items.GroupBy(property).Select(x => x.First());
}
但问题是我不想要ToList()我想要这样的东西
var spc = context.pcs.DistinctBy(w => w.province).Select(w => new
{
abc = w
}).ToList();
使用Async。但是找不到异步。如何让我的自定义方法distinctBy,所以我也可以异步使用它?
答案 0 :(得分:17)
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