MissingTime
MissingTime

Reputation: 36

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.

    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. I can get it to work if I use multiple string[] but I thought it would look cleaner with just a single 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.

Upvotes: 1

Views: 1799

Answers (3)

Furmek
Furmek

Reputation: 353

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";

Upvotes: 2

xsh
xsh

Reputation: 1

you must renew string[] before add to list.

Upvotes: -2

Sorceri
Sorceri

Reputation: 8033

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();

Upvotes: 2

Related Questions