How to return a list <class> in C #?

I tried to return List from method. But I only got the last iterations of the data in the list. Where did I go wrong? It overwrites the data in every loop in the list.

 public class ProjectData
 {
     public string name { get; set; }
     public string id { get; set; }
     public string web_url { get; set; }
 }

 public static List<ProjectData> GetProjectList()
 {
     int pageCount = 0;
     bool check = true;
     List<ProjectData> copy = new List<ProjectData>();
     List<ProjectData> projectData = new List<ProjectData>();

     while (check)
     {
         ProjectData NewProjectData = new ProjectData();
         pageCount = pageCount + 1;
         string userURL = "http://gitlab.company.com/api/v3/groups/450/projects?private_token=token&per_page=100&page=" + pageCount;
         HttpWebRequest requestforuser = (HttpWebRequest)WebRequest.Create(userURL);
         HttpWebResponse responseforuser = requestforuser.GetResponse() as HttpWebResponse;
         using (Stream responseStream = responseforuser.GetResponseStream())
         {
             StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
             var JSONString = reader.ReadToEnd();
             projectData = JsonConvert.DeserializeObject<List<ProjectData>>(JSONString);
             if (JSONString == "[]")
             {
                 check = false;
                 break;
             }
         }
         copy = projectData.ToList();
     }
     return copy;
 }

      

I know there are over 300 data available to populate the list. I tested it using a breakpoint. In this I found that all data was loaded correctly. But it was not copied to the list copy<>

. Each time it is overwritten in the list copy<>

. How do I prevent recording?

+3


source to share


2 answers


In each iteration, you overwrite the values ​​with the copy

current value in projectData

and only the last value will be returned. in fact, projectData

they copy

are of projectData

the same type, i.e. List<ProjectData>

so you don't need to convert them again as List with .ToList()

. In short, you should use like this:

copy.AddRange(projectData);

      



Instead for this copy = projectData.ToList();

+5


source


Replace copy = projectData.ToList();

withcopy.Add(projectData.ToList());



+1


source







All Articles