Async await in linq select

后端 未结 7 2347
醉酒成梦
醉酒成梦 2020-12-02 05:30

I need to modify an existing program and it contains following code:

var inputs = events.Select(async ev => await ProcessEventAsync(ev))
                          


        
7条回答
  •  旧时难觅i
    2020-12-02 05:41

    With current methods available in Linq it looks quite ugly:

    var tasks = items.Select(
        async item => new
        {
            Item = item,
            IsValid = await IsValid(item)
        });
    var tuples = await Task.WhenAll(tasks);
    var validItems = tuples
        .Where(p => p.IsValid)
        .Select(p => p.Item)
        .ToList();
    

    Hopefully following versions of .NET will come up with more elegant tooling to handle collections of tasks and tasks of collections.

提交回复
热议问题