簡體   English   中英

String.join在二維數組的一個維度上

[英]String.join on one dimension of a 2 dimensional array

我想用string.Join()打印一行我的二維數組,我找不到有效的方法。 當然我可以通過一個簡單的for循環來完成它,但知道是否有辦法可以做到這一點很有意思。

編輯我在談論一個普通的多維數組:

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

無法將行與正確的2D陣列隔離。 如果它是一個鋸齒狀陣列,那么解決方案就很明顯了。

因此,如果使用數組的行對您來說是重要的操作,那么您可以考慮將其轉換為鋸齒狀數組。

否則,如果這個操作不是很重要,那么循環是最不令人不安的方式。

您可以選擇為此目的添加一個簡單的擴展方法,並以這種方式將整個問題置於地毯下:

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];
    }
}

這將為您提供僅處理一行的選項:

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

例如,您可以在一行代碼中從矩陣中打印一行:

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

Zoran Horvat的答案很好,如果我需要做的就是讀數組,那就是我要做的。

如果您還需要編寫數組,可以執行以下操作:

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);
  }
}

而現在你有一些看起來像一維數組的東西實際寫入你的二維數組:

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

等等。

不知道你是否認為這比for循環更有效或可讀,但你可以這樣做:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM