【问题标题】:get first three elements of jagged array获取交错数组的前三个元素
【发布时间】:2011-09-22 02:38:56
【问题描述】:

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

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

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

【问题讨论】:

  • 请不要在标题前加上“C# LINQ”。这已经在标签中了。
  • @John Saunders,无论哪种方式,我都没有强烈的意见,但是如果您浏览问题标题列表,是否更容易在心理上进行排序?
  • Stack Overflow 上的人们习惯于使用标签来过滤问题列表,所以不,它没有。它只会使问题标题变得丑陋且难以阅读。自己阅读:“C# LINQ 获取锯齿状数组的前三个元素”与“获取锯齿状数组的前三个元素”。哪一个有意义并告诉您有关问题的一些信息,哪一个只是前面有东西?
  • @JohnSaunders,啊,我明白了,你说得很好。我以后会写干净的标题。

标签: c# winforms linq jagged-arrays


【解决方案1】:

如果您使用 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];

【讨论】:

  • 谢谢,我知道我已经很接近并围绕正确答案跳舞了。
  • 另外,之前从未使用过 .ToLookup() 。如果我能给你两次投票,我会的。
  • @jb。 - 是的,.ToLookup() 非常棒。干杯。
猜你喜欢
  • 2011-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-04
  • 1970-01-01
  • 1970-01-01
  • 2011-06-15
  • 1970-01-01
相关资源
最近更新 更多