保存来自 foreach c# 的多个响应

Saving multiple responses from foreach c#

正在创建使用集群名称从 AWS 获取服务名称的 C#/.net 应用程序。使用 AWS .net SDK

能够检索集群名称并将它们保存在字符串列表中:

AmazonECSClient client = new AmazonECSClient();
ListClustersRequest listClusterREquest = new ListClustersRequest();
var responseClusterList = await client.ListClustersAsync(listClusterREquest);
List<string> clusterArns = responseClusterList.ClusterArns;

现在尝试使用集群名称检索服务列表。我在将每个响应保存回名为 serviceArns 的列表时遇到问题。它只将最后一个响应保存到名为 serviceArns 的列表中。应该有大约 20 个回复保存到列表中。


ListServicesRequest listRequest = new ListServicesRequest();
List<string> serviceArns = null;
ListServicesResponse responsethree = new ListServicesResponse();

foreach (var item in clusterArns)
      {
                listRequest.Cluster = item;
                ListServicesResponse listResponse = await client.ListServicesAsync(listRequest);
    serviceArns = listResponse.ServiceArns;


};

您应该在开始时初始化列表并根据需要添加元素。目前,每次迭代都会设置列表,而应该在其中添加列表。

ListServicesRequest listRequest = new ListServicesRequest();
List<string> serviceArns = new();
ListServicesResponse responsethree = new ListServicesResponse();

foreach (var item in clusterArns)
{
    listRequest.Cluster = item;
    ListServicesResponse listResponse = await client.ListServicesAsync(listRequest);
    serviceArns.AddRange(listResponse.ServiceArns);
};