代码之家  ›  专栏  ›  技术社区  ›  GurdeepS

关于修改此自定义迭代器的问题

c#
  •  0
  • GurdeepS  · 技术社区  · 15 年前

    我有下面的代码,它基于自定义算法迭代列表:

            public static IEnumerable<TItem>
    MakeCustomIterator<TCollection, TCursor, TItem>(
    this TCollection collection, // Extension method of the collection used (eg List<T>)
    TCursor cursor, // An array of ints which holds our progress
    Func<TCollection, TCursor, TItem> getCurrent,
    Func<TCursor, bool> isFinished,
    Func<TCursor, TCursor> advanceCursor)
            {
                while (!isFinished(cursor)) // While we haven't reached the end of the iteration......
                {
                    yield return getCurrent(collection, cursor);
                    cursor = advanceCursor(cursor);
    
                }
    
            }
    
    
         var matrix = new List<List<double>> {
         new List<double> { 1.0, 1.1, 1.2 },
          new List<double> { 2.0, 2.1, 2.2 },
          new List<double> { 3.0, 3.1, 3.2 }
          };
    
         var iter = matrix.MakeCustomIterator(
         new int[] { 0, 0 },
         (coll, cur) => coll[cur[0]][cur[1]],
         (cur) => cur[0] > 2 || cur[1] > 2,
         (cur) => new int[] { cur[0] + 1,
           cur[1] + 1 });
    
    
    
                foreach (var item in iter)
                {
    
                }
    

    当我使用这个代码时,它将得到1.0,然后是2.1(在下一个列表中,斜下方)。在第一个链接中是否可以从1.0转到1.1?或者可以从1.0垂直向下移动到2.0?

    注意:此代码段来自Accelerated C 2008。

    谢谢

    1 回复  |  直到 15 年前
        1
  •  2
  •   Jon Skeet    15 年前

    你只需要改变“前进”是什么意思的想法(可能还有“完成”的意思)。例如,只需“向下”即可使用:

    var iter = matrix.MakeCustomIterator(
         new int[] { 0, 0 },
         (coll, cur) => coll[cur[0]][cur[1]],
         (cur) => cur[0] > 2 || cur[1] > 2,
         // Increase the row, but stay on the same column
         (cur) => new int[] { cur[0] + 1, cur[1] });
    

    “走”:

    var iter = matrix.MakeCustomIterator(
         new int[] { 0, 0 },
         (coll, cur) => coll[cur[0]][cur[1]],
         (cur) => cur[0] > 2 || cur[1] > 2,
         // Stay on the same row, but increase the column
         (cur) => new int[] { cur[0], cur[1] + 1 });
    

    “顺其自然”会更难,但可行:

    var iter = matrix.MakeCustomIterator(
         new int[] { 0, 0 },
         (coll, cur) => coll[cur[0]][cur[1]],
         (cur) => cur[0] > 2,
         // Stay on the same row if we can, otherwise move to next row
         (cur) => cur[1] == 2 ? new int[] { cur[0] + 1, 0 }
                              : new int[] { cur[0], cur[1] + 1});