一个有关数组的问题的解答
今天论坛上有这样一个问题:
我想用程序实现这样一种情况:
有一组数字:{1,2}{3,4}{5,6}
另一组数字:{11,12}{13,14}{15,16}
最后一组数字:{21,22}{23,24}{25,26}
想要这一段程序可以是这三组数字组合起来,
结果像这样:
1,2,11,12,21,22
3,4,11,12,21,11
...
其实就是每个大括号内算是一组数,然后和另一组大括号组合起来。
我想到的做法是下面的代码:
using System;
namespace ConsoleForTest
{
class Program
{
static void Main(string[] args)
{
int[][] arrOne = new int[3][];
arrOne[0] = new int[] { 1, 2 };
arrOne[1] = new int[] { 3, 4 };
arrOne[2] = new int[] { 5, 6 };
int[][] arrTwo = new int[3][];
arrTwo[0] = new int[] { 11, 12 };
arrTwo[1] = new int[] { 13, 14 };
arrTwo[2] = new int[] { 15, 16 };
int[][] arrThree = new int[3][];
arrThree[0] = new int[] { 21, 22 };
arrThree[1] = new int[] { 23, 24 };
arrThree[2] = new int[] { 25, 26 };
for (int i = 0; i < arrOne.Length; i++)
{
for (int j = 0; j < arrTwo.Length; j++)
{
for (int k = 0; k < arrThree.Length; k++)
{
Console.WriteLine(arrOne[i].GetArrayContent() + "," + arrTwo[j].GetArrayContent() + "," + arrThree[k].GetArrayContent());
}
}
}
Console.Read();
}
}
public static class ArrayExtend
{
/// <summary>
/// 获取数组内的各个元素的字符串整合表示形式
/// </summary>
/// <param name="arr">数组对象</param>
/// <returns>数组内的各个元素整合的字符串表示形式</returns>
public static string GetArrayContent(this Array arr)
{
if (arr == null)
return string.Empty;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for (int i = 0; i < arr.Length; i++)
{
sb.Append(',');
sb.Append(arr.GetValue(i));
}
if (sb.Length > 0)
sb.Remove(0, 1);
return sb.ToString();
}
}
}
namespace ConsoleForTest
{
class Program
{
static void Main(string[] args)
{
int[][] arrOne = new int[3][];
arrOne[0] = new int[] { 1, 2 };
arrOne[1] = new int[] { 3, 4 };
arrOne[2] = new int[] { 5, 6 };
int[][] arrTwo = new int[3][];
arrTwo[0] = new int[] { 11, 12 };
arrTwo[1] = new int[] { 13, 14 };
arrTwo[2] = new int[] { 15, 16 };
int[][] arrThree = new int[3][];
arrThree[0] = new int[] { 21, 22 };
arrThree[1] = new int[] { 23, 24 };
arrThree[2] = new int[] { 25, 26 };
for (int i = 0; i < arrOne.Length; i++)
{
for (int j = 0; j < arrTwo.Length; j++)
{
for (int k = 0; k < arrThree.Length; k++)
{
Console.WriteLine(arrOne[i].GetArrayContent() + "," + arrTwo[j].GetArrayContent() + "," + arrThree[k].GetArrayContent());
}
}
}
Console.Read();
}
}
public static class ArrayExtend
{
/// <summary>
/// 获取数组内的各个元素的字符串整合表示形式
/// </summary>
/// <param name="arr">数组对象</param>
/// <returns>数组内的各个元素整合的字符串表示形式</returns>
public static string GetArrayContent(this Array arr)
{
if (arr == null)
return string.Empty;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for (int i = 0; i < arr.Length; i++)
{
sb.Append(',');
sb.Append(arr.GetValue(i));
}
if (sb.Length > 0)
sb.Remove(0, 1);
return sb.ToString();
}
}
}
理解的越多,需要记忆的就越少