简体   繁体   English

控制台应用程序C#中的数组列表

[英]List of Array in console application C#

Im working on a school project and I havent found a working syntax for the last 2 hours. 我在一个学校的项目上工作,但在最近2小时内没有找到有效的语法。

    static void Main(string[] args)
    {

        List<string[]> loggBook = new List<string[]>();
        string[] loggBookArray = new string[2];

        loggBookArray[0] = "1";
        loggBookArray[1] = "2";
        loggBook.Add(loggBookArray);
        loggBookArray[0] = "3";
        loggBookArray[1] = "4";
        loggBook.Add(loggBookArray);
        loggBookArray[0] = "5";
        loggBookArray[1] = "6";
        loggBook.Add(loggBookArray);

        foreach (string[] x in loggBook)
        {
            string s = string.Join("\n", x);
            Console.WriteLine(s);
        }
        Console.ReadLine();

    }

Basically what this does is printing out 5,6,5,6,5,6 when I want it to print out 1,2,3,4,5,6. 当我希望它打印出1,2,3,4,5,6时,基本上这样做是打印出5,6,5,6,5,6。 I can get it to work if I use multiple string[] but I thought it would look cleaner with just a single string[]. 如果我使用多个string [],我可以使它工作,但我认为仅使用单个string []看起来就会更干净。 How do I get it to be saved the way I want? 我如何以我想要的方式保存它? Also, when they have been saved in the list, is there any way to edit the ones that have been put in the list? 此外,将它们保存在列表中后,是否有任何方法可以编辑已放入列表中的内容? Thanks in advance. 提前致谢。

you need to reinitialize the array after you add it otherwise you keep overwriting the same elements as the array is pointing to a specific memory address. 您需要在添加数组后重新初始化该数组,否则您将继续覆盖与该数组指向特定内存地址相同的元素。 Arrays are objects not value types 数组是对象而不是值类型

        List<string[]> loggBook = new List<string[]>();
        string[] loggBookArray;

        loggBookArray = new string[] { "1", "2" };
        loggBook.Add(loggBookArray);
        loggBookArray = new string[] { "3", "4" };
        loggBook.Add(loggBookArray);
        loggBookArray = new string[] { "5", "6" };
        loggBook.Add(loggBookArray);

        foreach (string[] x in loggBook)
        {
            string s = string.Join("\n", x);
            Console.WriteLine(s);
        }
        Console.ReadLine();

You could use collection initializes which would make the code shorter. 您可以使用集合初始化来缩短代码。

static void Main(string[] args)
{
    var loggBook = new List<string[]>
    {
        new[] {"1", "2"},
        new[] {"3", "4"},
        new[] {"5", "6"}
    };

    foreach (var x in loggBook)
    {
        var s = string.Join("\n", x);
        Console.WriteLine(s);
    }
    Console.ReadLine();
}

To edit and item you could access it by index like so: 要编辑项目,您可以按如下方式通过索引进行访问:

//Edit item (first element in the list, second in the array)
loggBook[0][1] = "0";

您必须先更新string []才能添加到列表中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM