[英]2D Array. Set all values to specific value
要為一維數組分配特定值,我正在使用 LINQ,如下所示:
int[] nums = new int[20];
nums = (from i in nums select 1).ToArray<int>();
nums[0] = 2;
在 2D ([x,y]) 數組中有類似的方法嗎? 或者簡短的方法,不使用嵌套循環?
如果你真的想避免嵌套循環,你可以只使用一個循環:
int[,] nums = new int[x,y];
for (int i=0;i<x*y;i++) nums[i%x,i/x]=n;
您可以通過將其放入實用程序類中的某個函數來使其更容易:
public static T[,] GetNew2DArray<T>(int x, int y, T initialValue)
{
T[,] nums = new T[x, y];
for (int i = 0; i < x * y; i++) nums[i % x, i / x] = initialValue;
return nums;
}
並像這樣使用它:
int[,] nums = GetNew2DArray(5, 20, 1);
LINQ 不適用於多維數組。
鋸齒狀數組還不錯:
var array = Enumerable.Range(0, 10)
.Select(x => Enumerable.Repeat('x', 10).ToArray())
.ToArray();
...但矩形陣列沒有任何特定的支持。 只需使用循環。
(注意使用Enumerable.Repeat
作為創建一維數組的更簡單的方法,順便說一句。)
嗯,這可能是作弊,因為它只是將循環代碼移動到擴展方法,但它確實允許您簡單地將 2D 數組初始化為單個值,其方式類似於將 1D 數組初始化為單個值的方式價值。
首先,正如 Jon Skeet 提到的,您可以像這樣清理初始化一維數組的示例:
int [] numbers = Enumerable.Repeat(1,20).ToArray();
使用我的擴展方法,您將能夠像這樣初始化一個二維數組:
public static T[,] To2DArray<T>(this IEnumerable<T> items, int rows, int columns)
{
var matrix = new T[rows, columns];
int row = 0;
int column = 0;
foreach (T item in items)
{
matrix[row, column] = item;
++column;
if (column == columns)
{
++row;
column = 0;
}
}
return matrix;
}
你可以這樣做的一種方法是這樣的:
// Define a little function that just returns an IEnumerable with the given value
static IEnumerable<int> Fill(int value)
{
while (true) yield return value;
}
// Start with a 1 dimensional array and then for each element create a new array 10 long with the value of 2 in
var ar = new int[20].Select(a => Fill(2).Take(10).ToArray()).ToArray();
我可以建議一種新的擴展方法。
public static class TwoDArrayExtensions
{
public static void ClearTo(this int[,] a, int val)
{
for (int i=a.GetLowerBound(0); i <= a.GetUpperBound(0); i++)
{
for (int j=a.GetLowerBound(1); j <= a.GetUpperBound(1); j++)
{
a[i,j] = val;
}
}
}
}
像這樣使用它:
var nums = new int[10, 10];
nums.ClearTo(1);
您可以創建一個循環所有元素並初始化它們的簡單方法:
public static void Fill2DArray<T>(T[,] arr, T value)
{
int numRows = arr.GetLength(0);
int numCols = arr.GetLength(1);
for (int i = 0; i < numRows; ++i)
{
for (int j = 0; j < numCols; ++j)
{
arr[i, j] = value;
}
}
}
這使用與 Array.Fill 相同的語法,適用於任何類型的數組
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.