如何异步组合多个列表

时间:2016-09-18 04:42:16

标签: c# async-await task

我没有得到如何将两个列表生成任务组合到一个公共列表中。以下代码不完整和/或错误,但我认为会让我陷入困境。 OrderFactory从Internet服务器请求数据。每个OrderFactory在将来某个时间完成,并且独立于任何其他OrderFactory。如何将每个任务返回的List订单合并到一个列表中?这两项任务都要一起开始,但将在不同的时间返回。

TIA

        private async Task<List<Orders>> GetReturnToOfficeOrdersAsync(PatientService patient)
        {
            var orders = new List<Orders>();
            var x =  await OrderFactory.CreateOrders(OrderType.RETURNTOOFFICE, patient);
            orders.AddRange(x);
            return orders;
        }

        private async Task<List<Orders>> GetProceduresAsync(PatientService patient)
        {
            var orders = new List<Orders>();
            var x = await OrderFactory.CreateOrders(OrderType.PROCEDURE, patient);
            orders.AddRange(x);
            return orders;
        }


        private async Task GetInCompleteOrderListAsync()
        {
            if (patient == null) return;

            var orders = new List<Orders>();

*** THE LISTS FROM THESE TASKS NEED TO BE COMBINED INTO ONE LIST -- HOW???    
            var a = GetReturnToOfficeOrdersAsync(patient);
            var b = GetProceduresAsync(patient);
            await Task.WhenAll(a, b);

            orders = orders.OrderByDescending(o => o.torder).ToList();

            IncompleteOrders = new ObservableCollection<Orders>(orders);
        }

1 个答案:

答案 0 :(得分:2)

如果您要将任务ab的结果添加到orders,您可以使用方法AddRange

var orders = new List<Orders>();

var a = GetReturnToOfficeOrdersAsync(patient);
var b = GetProceduresAsync(patient);

orders.AddRange(await a);    // add result of task a to the list
orders.AddRange(await b);    // add result of task b to the list