Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous Where Filter with Linq

I have a List of elements which is populated through an async call of a WebService (no problem there).

I need to filter that list in order to show something on the application view. I tried this:

List<DateTime> dates = EventsDates.Where(x => x.Day == tmp.Day && x.Month == tmp.Month && x.Year == tmp.Year).ToList();

I also tried using the Select function of LINQ. The problem is that any time this code is called, the EventsDates list isn't populated, the WebService hasn't responded yet.

How could I try to filter the EventsDates list asynchronously?

like image 905
Martin Stievenart Avatar asked Nov 24 '15 16:11

Martin Stievenart


3 Answers

"Where" shouldn't be async, you need to do EventsDates fill awaitable. Something like this:

EventsDates = await YourWebServiceMethodCall();
List<DateTime> dates = EventsDates.Where (x => x.Day == tmp.Day && x.Month == tmp.Month && x.Year == tmp.Year).ToList();
like image 153
Dmitriy Avatar answered Sep 28 '22 08:09

Dmitriy


You can call it asynchronously like this but as others have stated you need to await the eventDates to unwrap the response from the service before you use it. @Dmitry's answer is correct. I just put this here to answer your question of how to use Where asynchronously in case you need it in the future.

using System.Data.Entity;

List<DateTime> dates = await EventsDates.Where(x => x.Day == tmp.Day && x.Month == tmp.Month && x.Year == tmp.Year).ToListAsync();

You can also do this:

var list = someCollection.Where(async x => x.Prop == await SomeLongRunningProcess());
like image 35
Stephen Brickner Avatar answered Sep 28 '22 10:09

Stephen Brickner


It looks like you aren't awaiting the result to populate EventDates.

like image 26
Michael Blackburn Avatar answered Sep 28 '22 09:09

Michael Blackburn