如何在另一个已经存在的列表内的列表中添加值?

莫哈姆

新成员
已加入
2021年1月31日
留言内容
1
编程经验
Beginner
我有一个错误,并且不知道如何解决该错误,它是:我有一个列表,该列表又是类型<List <String>>,使用构造函数,我要做的是保存某些信息,接下来编写的代码是:



C#:
List<List<string>> opciones = new List<List<string>>();
        public Opcion(){
        var opcionesC = File.ReadAllText(this.dir).Split(";R;").ToList();
        opcionesC.RemoveAll(item => item == "");
        for(int i=0;i<opcionesC.Count;i++){
            this.opciones.Add(new List<string>());
            string[] opc= opcionesC[i].Split("\n");
            foreach(var t in opc){
                if(t.IndexOf("Marc")!=-1){
                    this.opciones[i].Add(t);                     //HERE ITS WORK
                }
                if(t.IndexOf("Model")!=-1){
                    this.opciones[i].Add(t.Remove(0,5));                      //HERE IS THE PROBLEM, NOT ADDING
                }
                if(t.IndexOf("Tip")!=-1){
                    this.opciones[i].Add(t.Remove(0,3));                      //HERE IS THE PROBLEM, NOT ADDING//El problema es esto, no se quiere añadir.
                    break;
                }
            }
        }
    }
然后在执行输出时得到以下信息:

C#:
 Marca: Audi
    Marca: BMW
我需要的是这样的输出:

C#:
Marca: Audi
    Modelo: A4
    Tipo: Turismo
    Marca: BMW
    Modelo: S3
    Tip:...
有人可以告诉我错误在哪里,谢谢!
 

附件

  • Captura de pantalla 2021-01-31 171352.png
    Captura de pantalla 2021-01-31 171352.png
    45 KB · Views: 6
由主持人最后编辑:

金西尼

C#论坛主持人
工作人员
已加入
2011年4月23日
留言内容
3,499
地点
悉尼,澳大利亚
编程经验
10+
Firs of all, it's rather silly to add a List<string> first and then get that back repeatedly. You should create the inner list and assign it to a variable, then populate it, then add it to the outer list as a final step.

As for the issue, the exception stack trace you attached seems to have little to do with the code you have posted. That stack trace indicates that you are calling Convert.ToInt32 on line 38 in the GetPunt method. Did you even look at that stack trace? You haven't told us where that line is and I don't see Convert.ToInt32 in your code anywhere. I suggest that you actually debug your code, i.e. set a breakpoint and then step through it line by line, confirming that all variables contain what you expect and and that execution follows the path that you expect. The exception you attached indicates that you're trying to convert a string to an int when it's not a valid representation of a number. You need to find out where that's happening and why and that's what the debugger is for.
 
最佳 底部