c# - 获取交错数组的前三个元素

标签 c# winforms linq jagged-arrays

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

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

enter image description here

这是我的(简化的)代码。 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];

关于c# - 获取交错数组的前三个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7508957/

相关文章:

C# 如何创建一组集合

.net - 处置SolidBrush和Pen是否重要?

c# - 在 LINQ 中分组时如何显式声明类型?

c# - 脚本# 包装 WebGL?

c# - 使用 ServiceStack.Text : determine JSON is Array, 对象或字符串?

c# - 作为代理或重定向器的负载平衡器

c#-3.0 - 如何从 TreeNode.FullPath 数据获取实际的树节点?

c# - 为 ListView 项目添加边框(仅围绕图像)

c# - 如何使用 LINQ to SQL 执行 CROSS JOIN?

c# - 按特定变量对类列表进行排序