Home > Software engineering >  c# output List<List<>> to the console
c# output List<List<>> to the console

Time:04-02

I want to test the function. and output List<List> to the console

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            List<List<int>> MoveLeftForawrd(List<int> Gameboard, int Y, int X)
            {
                  . . .

                return PossibleMoves;
            }
            
            List<List<int>> test = new List<List<int>> { };
            List<int> Gameboard = new List<int> { };
            int Currentplayer = 1;
            List<int> gameboard = new List<int> {
                -1,0,-1,0,-1,0,-1,0,
                0,-1,0,-1,0,-1,0,-1,
                -1,0,-1,0,-1,0,-1,0,
                0,0,0,0,0,0,0,0,
                0,0,0,0,0,0,0,0,
                0,1,0,1,0,1,0,1,
                1,0,1,0,1,0,1,0,
                0,1,0,1,0,1,0,1

                    };

            Gameboard = gameboard;

            test = MoveLeftForawrd(Gameboard, 5, 7);

            test.ForEach(Console.WriteLine);


        }
    }
}

but all I get is in the console..

System.Collections.Generic.List`1[System.Int32]

tell me, how do I correctly output list<list> to the console? I will be very grateful for your help.

CodePudding user response:

You have a list of lists:

List<List<int>> test = new List<List<int>> { };

So you could iterate over each list, and then iterate over the items in that list:

var count = 0;

foreach(var outerItem in test)
{
    foreach(var innerItem in outerItem)
    {
        if(count>0)
        {
            Console.Write(",");
        }

        Console.Write($"{innerItem}");
        if(count   == 8)
        {
           Console.WriteLine();
           count = 0;
        }
    }
}

CodePudding user response:

You can try using string.Join and pinch of Linq in order to get string from List<string>:

List<List<int>> PossibleMoves = ...

...

string report = string.Join(Environment.NewLine, PossibleMoves
  .Select(line => string.Join(" ", line.Select(item => $"{item,3}")));

Console.WriteLine(report);

Here we join items in each line with space:

string.Join(" ", line.Select(item => $"{item,3}"))

e.g. {1, 0, -1, 0} will be " 1 0 -1 0"

and then join lines with Environment.NewLine to get something like

 1  0 -1  0
-1  0  0  0
 0 -1  1 -1

CodePudding user response:

You can do this simply using layered foreach loops e.g.

    List<List<int>> Lists = new List<List<int>>(){new List<int>(){1,2,3,4,5},
    new List<int>(){6,7,8,9,0},
    new List<int>(){1,2,3,4,5}};
    
    foreach(var list in Lists)
    {
        foreach(var c in list)
        {
            Console.Write($" {c} ");
        }
        Console.WriteLine("");
    }

Output:

 1  2  3  4  5 
 6  7  8  9  0 
 1  2  3  4  5 
  • Related