奇怪的数组行为

Arn*_* F. 2 c# linq arrays

我观察到一种非常奇怪的行为,也许你可以帮助我看看会发生什么.

这里的课程:

public sealed class Sudoku
{
    private SudokuCell[] _grid = new SudokuCell[81];

    // ctor {}

    private IEnumerable<SudokuCell> Grid
    {
        get { return _grid; }
    }

    private SudokuRow[] _rows;
    public IEnumerable<SudokuRow> Rows
    {
        get
        {
            if (_rows == null)
            {
                _rows = new SudokuRow[9];

                for (int i = 0, length = 9; i < length; i++)
                {
                    _rows[i] = new SudokuRow(from cell in Grid
                                             where cell.Row == i
                                             select cell);

                    // Always print 9 (GOOD)
                    Trace.WriteLine("First Loop " + i + " : " + _rows[i].Cells.Count());
                }
            }

            for (int i = 0; i < 9; i++)
            {
                // Always print 0 ! Huh !?
                Trace.WriteLine("Second Loop " + i + " : " + _rows[i].Cells.Count());
            }

            return _rows;
        }
    }
}

public abstract class SudokuPart
{
    public SudokuPart(IEnumerable<SudokuCell> cells)
    {
        Cells = cells;
    }

    public int Index
    { get; protected set; }

    public IEnumerable<SudokuCell> Cells
    { get; protected set; }
}

public sealed class SudokuRow : SudokuPart
{
    public SudokuRow(IEnumerable<SudokuCell> cells)
        : base(cells)
    {
        base.Index = cells.First().Row;
    }
}
Run Code Online (Sandbox Code Playgroud)

谁能告诉我为什么在第二个循环中它跟踪0而不是9!我在两个循环之间都没有改变!

谢谢...

Jon*_*eet 10

这就是问题:

_rows[i] = new SudokuRow(from cell in Grid
                         where cell.Row == i
                         select cell);
Run Code Online (Sandbox Code Playgroud)

这是捕获循环变量(i)... 的循环,它有一个合理的值,这就是为什么你看到9场比赛.

但是,当您计算第二个循环中的匹配值时,该单个捕获的变量将具有值9.现在没有 cell.Row值为9,因此您没有获得任何匹配.有关这方面的更多信息,请参阅Eric Lippert的精彩博文,"关闭循环变量被视为有害".

三个修复:

  • 捕获循环变量的副本:

    int copy = i;
    _rows[i] = new SudokuRow(from cell in Grid
                             where cell.Row == copy
                             select cell);
    
    Run Code Online (Sandbox Code Playgroud)

    循环的每次迭代都将获得一个单独的副本.

  • 在循环中实现查询:

    _rows[i] = new SudokuRow((from cell in Grid
                             where cell.Row == i
                             select cell).ToList());
    
    Run Code Online (Sandbox Code Playgroud)

    甚至:

    _rows[i] = new SudokuRow(Grid.Where(cell => cell.Row == i).ToList());
    
    Run Code Online (Sandbox Code Playgroud)
  • 根本不要使用LINQ!为什么不只是有一个数组数组来表示网格?这是一种更自然的方法,IMO.