Passing one Dimension of a Two Dimensional Array in C#

后端 未结 6 943
耶瑟儿~
耶瑟儿~ 2021-01-21 07:31

I have moved from C to C#. I have a function which accepts an array. I want to pass one dimension of a Two Dimensional array to this function.

C Code would be:-

6条回答
  •  佛祖请我去吃肉
    2021-01-21 08:02

    You can't really do that. C# is less outgoing about its arrays, and prevents you from doing C-like manipulations. This is a good thing.

    You have various options:

    1. Create a 1D array and copy your 2D row to it.
    2. Use a jagged array - an array of arrays, which is more like what C lets you do.
    3. Have an array_processing overload that takes a 2D array and a row number.

    4. If you really want to access a 2D row as a 1D array, you should create a 'RowProxy' class that will implement the IList interface and let you access just one row:

      class RowProxy: IList
      {
          public RowProxy(T[,] source, int row)
          { 
             _source = source;
             _row = row;
          }
      
          public T this[int col]
          {
              get { return _source[_row, col]; } 
              set { _source[_row, col] = value; }
          }
      
          private T[,] _source;
          private int _row;
      
          // Implement the rest of the IList interface
      }
      
    5. Use a lambda expression that will lose the array semantics, but is rather cool:

      var ClientId = ...;
      
      var row_5_accessor = (c=>ClientId[5, c]);
      

      You can use row_5_accessor as a function, row_5_accessor(3) will give you ClientId[5, 3]

提交回复
热议问题