如何在c#中返回<class>列表?

3 c# json list

我试图从一个方法返回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;
 }
Run Code Online (Sandbox Code Playgroud)

我知道有300多个数据可以填写清单.我用断点检查了它.在那,我发现所有数据都正确获取.但它没有被复制到copy<>列表中.每次都在copy<>列表中被覆盖.如何防止过度写作?

suj*_*lil 5

在每次迭代中,您将copy使用当前值覆盖值,projectData并且仅返回最后一个值.其实projectDatacopy是同一类型,例如,List<ProjectData>所以你不需要他们通过再次转换为一个列表.ToList().总之,你必须这样使用:

copy.AddRange(projectData);
Run Code Online (Sandbox Code Playgroud)

而是为此 copy = projectData.ToList();