【问题标题】:How to add value to a list in class that have a string array?如何向具有字符串数组的类中的列表添加值?
【发布时间】:2020-02-14 11:20:22
【问题描述】:

我正在创建一个包含小组赛和淘汰赛的锦标赛应用程序。我正在使用带有列表的类来创建不同的组,以便稍后将它们保存到 xml 文件中。

这就是我的列表和类的样子 (xmlHandlerScript)。

public void AddGroup(int group,string[] team)
{

    groupDB.list.Add(new Groups { groupIndex = group, team = team });   
}

public GroupDatabse groupDB;

[System.Serializable]
public class Groups
{
    public int groupIndex;
    public string[] team;          
}

[System.Serializable]
public class GroupDatabse
{
    public List<Groups> list = new List<Groups>();
}

这就是我为列表变量添加值的方式。

 groups = new string[totalTeamsPerGroup];
 int  j = 0;

  for(int i = 0; i < totalGroups; i++)
  {
        for (int x = 0; x < totalTeamsPerGroup; x++)
        {

            groups[x] = teams[j];                   
            j++;
        }
            xmlHandlerScript.AddGroup(i, groups);

   }

我的问题是当我有超过 1 个“totalGroups”并将数组“groups”添加到列表中时,string[] 团队 em> 被我的两个数组中的最后一个 teams[] 替换

像这样:

Teams in Tournument Groups after i added them to list

【问题讨论】:

    标签: arrays list class


    【解决方案1】:

    试试这个 - 您需要为每个团队迭代重新初始化组列表。我使用 List 而不是数组,因为 C# 中的 List 更易于管理。

     int  j = 0;
    
      for(int i = 0; i < totalGroups; i++)
      {
           var groups = new List<string>();
            for (int x = 0; x < totalTeamsPerGroup; x++)
            {
    
                groups.Add(teams[j]);                   
                j++;
            }
                xmlHandlerScript.AddGroup(i, groups);
    
       }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-27
      • 1970-01-01
      相关资源
      最近更新 更多