如何防止在我的解决方案中重复共同循环?

时间:2011-05-04 20:32:27

标签: c# .net code-duplication jagged-arrays

我有一个基于锯齿状数组的循环,我需要在不同的地方使用不止一次。

我怎样才能阻止自己一次又一次地重写这个循环,以便我会复制它?

      foreach (int[] columns in rowsAndColumns)
      {
          foreach (int element in columns)
          {

          }
      }

5 个答案:

答案 0 :(得分:8)

你可以写

foreach (int element in rowsAndColumns.SelectMany(col => col))
{
    // ...
}

代替。如果您不想一直打字,可以将其抽象为辅助方法:

foreach (int element in rowsAndColumns.Flatten())
{
    // ...
}

// [...]

public IEnumerable<T> Flatten(this IEnumerable<IEnumerable<T>> source)
{
    return source.SelectMany(e => e);
}

答案 1 :(得分:1)

这取决于你想要做什么,但如果你想对每个int执行一个动作,你可以选择下面的扩展名。可能需要进行一些空检查。

static class RowColExtension
{
    public static void Each(this int[][] rowCols, Action<int> a)
    {
        foreach (var r in rowCols)
        {
            foreach (var c in r)
            {
                a(c);
            }
        }
    }
}

答案 2 :(得分:0)

这取决于你想在循环中做什么。我会像这样接近它(我的头脑中未经测试的代码!):

public static class MyHelper {
    public static void ForEach(this IEnumerable<int[]> rowsAndColumns, Action<int> action) {
        foreach (int[] columns in rowsAndColumns) {
             foreach (int element in columns) {
                 action(element);
             }
        }
    }
}

现在你可以这样称呼它:

rowsAndColumns.ForEach(e => Console.WriteLine(e));

答案 3 :(得分:0)

扩展方法:

// It's late and I'm tired, the array declaration might be off.
public static void Visit(this int[][] array, Action<int> visitor)
{
      foreach (int[] columns in array)
      {
          foreach (int element in columns)
          {
              visitor(element);
          }
      }
}

myArray.Visit(elem => Console.WriteLine(elem));

您也可以使用Action<int,int>获取该行。

答案 4 :(得分:0)

由于您在不考虑行或列的情况下迭代所有元素,因此应将锯齿状数组转换为第一类数据结构,并使用IEnumerable实现foreach迭代集合。相同的第一类数据结构可以支持单参数和双参数索引器,范围检查等。

修改

这是一种使用抽象而不是操纵低级数据结构的方法。这假设锯齿状阵列在其他地方分配。无论哪种方式,重点是我们现在可以直接在数据结构上使用foreach

public class JaggedArray : IEnumerable<int>
{
    private int[][] array;

    public JaggedArray(int[][] array)
    {
        this.array = array;
    }

    public int this[int row, int column]
    {
        get { return array[row][column]; }
        set { array[row][column] = value; }
    }

    public IEnumerable<int[]> Rows
    {
        get { return array; }
    }

    public IEnumerator<int> GetEnumerator()
    {
        foreach (var row in array)
            foreach (var item in row)
                yield return item;
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}