现在的位置: 首页 > 综合 > 正文

一个有关数组的问题的解答

2011年01月13日 ⁄ 综合 ⁄ 共 1974字 ⁄ 字号 评论关闭

今天论坛上有这样一个问题:

我想用程序实现这样一种情况:
有一组数字:{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[] { 12 };
            arrOne[
1= new int[] { 34 };
            arrOne[
2= new int[] { 56 };

            int[][] arrTwo = new int[3][];
            arrTwo[
0= new int[] { 1112 };
            arrTwo[
1= new int[] { 1314 };
            arrTwo[
2= new int[] { 1516 };

            int[][] arrThree = new int[3][];
            arrThree[
0= new int[] { 2122 };
            arrThree[
1= new int[] { 2324 };
            arrThree[
2= new int[] { 2526 };

            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(
01);
            
return sb.ToString();
        }
    }
}

 

抱歉!评论已关闭.