开发者

get first three elements of jagged array

My brain isn't working, I'm trying to grab the first three rows on this grid. I'm making a simple checkers game just to learn some new stuff. My code is grabbing the first three columns to initialize the placement of the red chess pieces. I want the first three rows instead.

This is what my code is doing now:

get first three elements of jagged array

This is my (simplified) code. Square is a class of mine that just holds a few little items to keep track of pieces.

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


If you are using m_board.Take(3) to get the first three columns, then this should give you the first three rows:

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

If you want to get the rows (or columns) as enumerables then do this:

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];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜