3

我的大脑不工作了,我试图抓住这个网格上的前三行。我正在制作一个简单的跳棋游戏,只是为了学习一些新东西。我的代码正在抓取前三列来初始化红色棋子的位置。我想要前三行。

这就是我的代码现在正在做的事情:

在此处输入图像描述

这是我的(简化的)代码。Square是我的一类,它只保存一些小物品来跟踪碎片。

    private Square[][] m_board = new Square[8][];
    for (int i = 0; i < m_board.Length; i++)
        m_board[i] = new Square[8];


//find which pieces should hold red pieces, the problem line
    IEnumerable<Square> seqRedSquares = 
         m_board.Take(3).SelectMany(x => x).Where(x => x != null);
//second attempt with the same result
    //IEnumerable<Square> seqRedSquares = 
         m_board[0].Union(m_board[1]).Union(m_board[2]).Where(x => x != null);

//display the pieces, all works fine
    foreach (Square redSquare in seqRedSquares)
    {
        Piece piece = new Piece(redSquare.Location, Piece.Color.Red);
        m_listPieces.Add(piece);
        redSquare.Update(piece);
    }
4

1 回答 1

3

如果您m_board.Take(3)用于获取前三列,那么这应该为您提供前三行:

 m_board.Select(c => c.Take(3))

如果您想将行(或列)作为可枚举项,请执行以下操作:

var flattened = m_board
    .SelectMany((ss, c) =>
        ss.Select((s, r) =>
            new { s, c, r }))
    .ToArray();

var columns = flattened
    .ToLookup(x => x.c, x => x.s);

var rows = flattened
    .ToLookup(x => x.r, x => x.s);

var firstColumn = columns[0];
var thirdRow = rows[2];
于 2011-09-22T02:57:18.413 回答