簡體   English   中英

c# output 列表<list<> > 到控制台</list<>

[英]c# output List<List<>> to the console

我想測試 function. 和 output List<List> 到控制台

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


        }
    }
}

但我得到的只是在控制台中..

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

告訴我,我如何正確地將 output list<list> 發送到控制台? 我將非常感謝你的幫助。

你有一個列表列表:

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

因此,您可以遍歷每個列表,然后遍歷該列表中的項目:

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

您可以嘗試使用string.Join和捏合Linq以從List<string>獲取string

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

...

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

Console.WriteLine(report);

在這里,我們用空格連接每行中的項目:

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

例如{1, 0, -1, 0}將是" 1 0 -1 0"

然后加入Environment.NewLine行以獲得類似

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

您可以簡單地使用分層 foreach 循環來做到這一點,例如

    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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM