Home > Software engineering >  Saving multiple responses from foreach c#
Saving multiple responses from foreach c#

Time:12-24

Creating C#/.net application that gets services names from AWS using the cluster name. With the AWS .net SDK

Able to retrieve cluster names and save them in a list of strings:

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

Now trying to retrieve the list of services using the cluster names. I am having issues saving each response back to a list named serviceArns. It only saves the last response to the list called serviceArns. There should be about 20 responses saved to the list.


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;


};

CodePudding user response:

You should intialise the list at the start and add elements as needed be. Currently with each iteration, the list gets set, where it should be adding it instead.

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);
};
  • Related