我的大脑无法正常工作,我正在尝试抓住该网格上的前三行.我正在制作一个简单的跳棋游戏,只是为了学习一些新知识.我的代码抓住了前三列,以初始化红色棋子的放置.我想要前三行.
这是我的代码现在正在做的事情:
这是我的(简化)代码. 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);
}
解决方法:
如果您使用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];