简体   繁体   中英

String.join on one dimension of a 2 dimensional array

I want to print a row of my 2-dimensional array with string.Join() and I couldn't find a way to do it efficiently. Of course I could do it with a simple for loop but it would be interesting to know if there is a way to do it.

EDIT I'm talking about a normal multidimensional array:

int[,] multidimensionalArray= new int[,];

No way to isolate a row from a proper 2D array. If it were a jagged array, then the solution would be obvious.

Therefore, if working with rows of the array is important operation to you, then you might consider turning it into the jagged array.

Otherwise, if this operation is not of fundamental importance, then a loop is the least disturbing way to go.

You may choose to add a simple extension method for this purpose, and in that way put entire problem under the rug:

public static class ArrayExtensions
{
    public static IEnumerable<T> GetRow<T>(this T[,] array, int rowIndex)
    {
        int columnsCount = array.GetLength(1);
        for (int colIndex = 0; colIndex < columnsCount; colIndex++)
            yield return array[rowIndex, colIndex];
    }
}

This would give you the option to address only one row:

IEnumerable<int> row = array.GetRow(1);

For example, you could print one row from the matrix in one line of code:

Console.WriteLine(string.Join(", ", array.GetRow(1).ToArray()));

The answer of Zoran Horvat is good and that's what I would do if all I needed to do was read the array.

If you also needed to write the array, you might do something like this:

struct ArrayRow<T> // Consider implementing IEnumerable<T>
{
  T[,] array;
  int row;
  public ArrayRow(T[,] array, int row) 
  { 
    this.array = array; 
    this.row = row;
  }
  public T this[int i]
  {
    get { return this.array[this.row, i]; }
    set { this.array[this.row, i] = value; }
  }
  public int Length 
  {
    get { return this.array.GetLength(1); }
  }
  public IEnumerable<T> Items ()
  {
    int c = this.Length;
    for (int i = 0; i < c; ++i)
      yield return this[i];
  }
}

static class Extensions 
{
  public static ArrayRow<T> GetRow<T>(this T[,] array, int row)
  {
    return new ArrayRow<T>(array, row);
  }
}

And now you have something that looks like a one-dimensional array that actually writes to your two-dimensional array:

var myRow = myArray.GetRow(10);
myRow[20] += 30;
string.Join(",", myRow.Items());

And so on.

Don't know if you regard this more efficient or readable than a for loop, but you can do this:

string s = string.Join(separator,
                       Enumerable.Range(0, multidimentionalarray.GetLength(1))
                                 .Select(column => multidimentionalarray[row, column]));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM