你如何循环多维数组?

时间:2021-04-28 21:35:36
foreach (String s in arrayOfMessages)
{
    System.Console.WriteLine(s);
}

string[,] arrayOfMessages is being passed in as a parameter.

string [,] arrayOfMessages作为参数传入。

I want to be able to determine which strings are from arrayOfMessages[0,i] and arrayOfMessages[n,i], where n is the final index of the array.

我希望能够确定哪些字符串来自arrayOfMessages [0,i]和arrayOfMessages [n,i],其中n是数组的最终索引。

6 个解决方案

#1


32  

Simply use two nested for loops. To get the sizes of the dimensions, you can use GetLength():

只需使用两个嵌套的for循环。要获取尺寸的大小,可以使用GetLength():

for (int i = 0; i < arrayOfMessages.GetLength(0); i++)
{
    for (int j = 0; j < arrayOfMessages.GetLength(1); j++)
    {
        string s = arrayOfMessages[i, j];
        Console.WriteLine(s);
    }
}

This assumes you actually have string[,]. In .Net it's also possible to have multidimensional arrays that aren't indexed from 0. In that case, they have to be represented as Array in C# and you would need to use GetLowerBound() and GetUpperBound() the get the bounds for each dimension.

这假设你实际上有字符串[,]。在.Net中,也可以使用不从0开始索引的多维数组。在这种情况下,它们必须在C#中表示为Array,并且您需要使用GetLowerBound()和GetUpperBound()来获取每个数组的边界。尺寸。

#2


7  

With a nested for loop:

使用嵌套for循环:

for (int row = 0; row < arrayOfMessages.GetLength(0); row++)
{
   for (int col = 0; col < arrayOfMessages.GetLength(1); col++)
   {
      string message = arrayOfMessages[row,col];
      // use the message
   }    
}

#3


6  

Don't use foreach - use nested for loops, one for each dimension of the array.

不要使用foreach - 使用嵌套for循环,一个用于数组的每个维度。

You can get the number of elements in each dimension with the GetLength method.

您可以使用GetLength方法获取每个维度中的元素数量。

See Multidimensional Arrays (C# Programming Guide) on MSDN.

请参阅MSDN上的多维数组(C#编程指南)。

#4


1  

Something like this would work:

这样的东西会起作用:

int length0 = arrayOfMessages.GetUpperBound(0) + 1;
int length1 = arrayOfMessages.GetUpperBound(1) + 1;

for(int i=0; i<length1; i++) { string msg = arrayOfMessages[0, i]; ... }
for(int i=0; i<length1; i++) { string msg = arrayOfMessages[length0-1, i]; ... }

#5


1  

You can use the code below to run multidimensional arrays.

您可以使用下面的代码来运行多维数组。

foreach (String s in arrayOfMessages)
{
    System.Console.WriteLine("{0}",s);
}

#6


1  

It looks like you found an answer suitable for your problem, but since the title asks for a multidimensional array (which I read as 2 or more), and this is the first search result I got when searching for that, I'll add my solution:

看起来你找到了一个适合你的问题的答案,但由于标题要求一个多维数组(我读为2或更多),这是我搜索时得到的第一个搜索结果,我将添加我的解:

public static class MultidimensionalArrayExtensions
{
    /// <summary>
    /// Projects each element of a sequence into a new form by incorporating the element's index.
    /// </summary>
    /// <typeparam name="T">The type of the elements of the array.</typeparam>
    /// <param name="array">A sequence of values to invoke the action on.</param>
    /// <param name="action">An action to apply to each source element; the second parameter of the function represents the index of the source element.</param>
    public static void ForEach<T>(this Array array, Action<T, int[]> action)
    {
        var dimensionSizes = Enumerable.Range(0, array.Rank).Select(i => array.GetLength(i)).ToArray();
        ArrayForEach(dimensionSizes, action, new int[] { }, array);
    }
    private static void ArrayForEach<T>(int[] dimensionSizes, Action<T, int[]> action, int[] externalCoordinates, Array masterArray)
    {
        if (dimensionSizes.Length == 1)
            for (int i = 0; i < dimensionSizes[0]; i++)
            {
                var globalCoordinates = externalCoordinates.Concat(new[] { i }).ToArray();
                var value = (T)masterArray.GetValue(globalCoordinates);
                action(value, globalCoordinates);
            }
        else
            for (int i = 0; i < dimensionSizes[0]; i++)
                ArrayForEach(dimensionSizes.Skip(1).ToArray(), action, externalCoordinates.Concat(new[] { i }).ToArray(), masterArray);
    }

    public static void PopulateArray<T>(this Array array, Func<int[], T> calculateElement)
    {
        array.ForEach<T>((element, indexArray) => array.SetValue(calculateElement(indexArray), indexArray));
    }
}

Usage example:

用法示例:

var foo = new string[,] { { "a", "b" }, { "c", "d" } };
foo.ForEach<string>((value, coords) => Console.WriteLine("(" + String.Join(", ", coords) + $")={value}"));
// outputs:
// (0, 0)=a
// (0, 1)=b
// (1, 0)=c
// (1, 1)=d

// Gives a 10d array where each element equals the sum of its coordinates:
var bar = new int[4, 4, 4, 5, 6, 5, 4, 4, 4, 5];
bar.PopulateArray(coords => coords.Sum());

General idea is to recurse down through dimensions. I'm sure the functions won't win efficiency awards, but it works as a one-off initialiser for my lattice and comes with a nice-enough ForEach that exposes the values and indices. Main downside I haven't solved is getting it to automatically recognise T from the Array, so some caution is required when it comes to the type safety.

一般的想法是通过维度进行递减。我确信这些功能不会赢得效率奖励,但它可以作为我的格子的一次性初始化器,并带有一个足够好的ForEach来暴露价值和指数。我还没有解决的主要缺点是让它自动识别阵列中的T,因此在类型安全方面需要谨慎。

#1


32  

Simply use two nested for loops. To get the sizes of the dimensions, you can use GetLength():

只需使用两个嵌套的for循环。要获取尺寸的大小,可以使用GetLength():

for (int i = 0; i < arrayOfMessages.GetLength(0); i++)
{
    for (int j = 0; j < arrayOfMessages.GetLength(1); j++)
    {
        string s = arrayOfMessages[i, j];
        Console.WriteLine(s);
    }
}

This assumes you actually have string[,]. In .Net it's also possible to have multidimensional arrays that aren't indexed from 0. In that case, they have to be represented as Array in C# and you would need to use GetLowerBound() and GetUpperBound() the get the bounds for each dimension.

这假设你实际上有字符串[,]。在.Net中,也可以使用不从0开始索引的多维数组。在这种情况下,它们必须在C#中表示为Array,并且您需要使用GetLowerBound()和GetUpperBound()来获取每个数组的边界。尺寸。

#2


7  

With a nested for loop:

使用嵌套for循环:

for (int row = 0; row < arrayOfMessages.GetLength(0); row++)
{
   for (int col = 0; col < arrayOfMessages.GetLength(1); col++)
   {
      string message = arrayOfMessages[row,col];
      // use the message
   }    
}

#3


6  

Don't use foreach - use nested for loops, one for each dimension of the array.

不要使用foreach - 使用嵌套for循环,一个用于数组的每个维度。

You can get the number of elements in each dimension with the GetLength method.

您可以使用GetLength方法获取每个维度中的元素数量。

See Multidimensional Arrays (C# Programming Guide) on MSDN.

请参阅MSDN上的多维数组(C#编程指南)。

#4


1  

Something like this would work:

这样的东西会起作用:

int length0 = arrayOfMessages.GetUpperBound(0) + 1;
int length1 = arrayOfMessages.GetUpperBound(1) + 1;

for(int i=0; i<length1; i++) { string msg = arrayOfMessages[0, i]; ... }
for(int i=0; i<length1; i++) { string msg = arrayOfMessages[length0-1, i]; ... }

#5


1  

You can use the code below to run multidimensional arrays.

您可以使用下面的代码来运行多维数组。

foreach (String s in arrayOfMessages)
{
    System.Console.WriteLine("{0}",s);
}

#6


1  

It looks like you found an answer suitable for your problem, but since the title asks for a multidimensional array (which I read as 2 or more), and this is the first search result I got when searching for that, I'll add my solution:

看起来你找到了一个适合你的问题的答案,但由于标题要求一个多维数组(我读为2或更多),这是我搜索时得到的第一个搜索结果,我将添加我的解:

public static class MultidimensionalArrayExtensions
{
    /// <summary>
    /// Projects each element of a sequence into a new form by incorporating the element's index.
    /// </summary>
    /// <typeparam name="T">The type of the elements of the array.</typeparam>
    /// <param name="array">A sequence of values to invoke the action on.</param>
    /// <param name="action">An action to apply to each source element; the second parameter of the function represents the index of the source element.</param>
    public static void ForEach<T>(this Array array, Action<T, int[]> action)
    {
        var dimensionSizes = Enumerable.Range(0, array.Rank).Select(i => array.GetLength(i)).ToArray();
        ArrayForEach(dimensionSizes, action, new int[] { }, array);
    }
    private static void ArrayForEach<T>(int[] dimensionSizes, Action<T, int[]> action, int[] externalCoordinates, Array masterArray)
    {
        if (dimensionSizes.Length == 1)
            for (int i = 0; i < dimensionSizes[0]; i++)
            {
                var globalCoordinates = externalCoordinates.Concat(new[] { i }).ToArray();
                var value = (T)masterArray.GetValue(globalCoordinates);
                action(value, globalCoordinates);
            }
        else
            for (int i = 0; i < dimensionSizes[0]; i++)
                ArrayForEach(dimensionSizes.Skip(1).ToArray(), action, externalCoordinates.Concat(new[] { i }).ToArray(), masterArray);
    }

    public static void PopulateArray<T>(this Array array, Func<int[], T> calculateElement)
    {
        array.ForEach<T>((element, indexArray) => array.SetValue(calculateElement(indexArray), indexArray));
    }
}

Usage example:

用法示例:

var foo = new string[,] { { "a", "b" }, { "c", "d" } };
foo.ForEach<string>((value, coords) => Console.WriteLine("(" + String.Join(", ", coords) + $")={value}"));
// outputs:
// (0, 0)=a
// (0, 1)=b
// (1, 0)=c
// (1, 1)=d

// Gives a 10d array where each element equals the sum of its coordinates:
var bar = new int[4, 4, 4, 5, 6, 5, 4, 4, 4, 5];
bar.PopulateArray(coords => coords.Sum());

General idea is to recurse down through dimensions. I'm sure the functions won't win efficiency awards, but it works as a one-off initialiser for my lattice and comes with a nice-enough ForEach that exposes the values and indices. Main downside I haven't solved is getting it to automatically recognise T from the Array, so some caution is required when it comes to the type safety.

一般的想法是通过维度进行递减。我确信这些功能不会赢得效率奖励,但它可以作为我的格子的一次性初始化器,并带有一个足够好的ForEach来暴露价值和指数。我还没有解决的主要缺点是让它自动识别阵列中的T,因此在类型安全方面需要谨慎。