2012-03-27 161 views
8

所有值要指定特定的值,以一維數組我使用LINQ像這樣:二維數組。設置爲特定值

 int[] nums = new int[20]; 
     nums = (from i in nums select 1).ToArray<int>(); 
     nums[0] = 2; 

有類似的方式在2D這麼做([X,Y])陣列? 或簡短的方式,不使用嵌套循環?

+5

你不是在一個陣列設置值,您創建內部數組*新*陣列 – vidstige 2012-03-27 16:59:28

回答

6

對於多維數組,LINQ不能很好地工作。

鐵血陣列都差不太多:

var array = Enumerable.Range(0, 10) 
         .Select(x => Enumerable.Repeat('x', 10).ToArray()) 
         .ToArray(); 

...但矩形陣列沒有任何具體的支持。只需使用循環。

(注意用Enumerable.Repeat作爲一個較爲簡單的方法來創建一維數組,順便說一句),你可以做到這一點

+0

這不是我所需要的,它的陣列。 – 2012-03-27 17:01:43

1

一種方式是像這樣:

// 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(); 
+0

謝謝,但它是數組內的數組。我正在尋找如何在二維數組中做到這一點[x,y] – 2012-03-27 17:06:11

5

如果你真的要避免嵌套的循環,你可以只使用一個循環:

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); 
+0

好主意,但它在我看來太難了。我正在尋找像LINQ這樣簡單的東西。 – 2012-03-27 17:45:01

+2

此答案中的前兩個(TWO !!)代碼行解決了您的問題。我不緊湊格式化,可能看起來很醜,但你不能得到任何更簡單,更小,更快。 – heltonbiker 2014-06-03 13:39:54

+0

與嵌套for循環相比,這樣一個for循環會更快嗎? – juFo 2017-10-05 14:17:37

3

那麼,這可能會被欺騙,因爲它只是將循環代碼擴展方法,但它允許您將二維數組初始化到一個值的簡單方式,並且類似於如何將一維數組初始化爲單個值的方式。

首先,喬恩斯基特提到的,你可以清理你的初始化一維數組像這樣的例子:

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; 
} 
+0

這個擴展方法沒有理由不是通用的,我相應地更新了它。 – 2015-10-22 11:54:03

1

我可以提出一種新的擴展方法。

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