创建一个正常数组,其中一个位置可以包含多个值

时间:2015-11-24 14:05:04

标签: c# arrays

我正在创建一个数组,其中数组上的一个位置需要有两个值,但每个其他位置都有一个值。

例如:

Public int[] Array = new int[10];
for (int i = 1; i <11; i++)
{
   array[i] = 1
   if (i = 1)
     {
       array[i] also = 2
     }
}

简而言之,我想拥有以下内容:

[0] 0

[1] 1 2

[2] 1

[3] 1

3 个答案:

答案 0 :(得分:3)

您可以使用锯齿状数组

public int[][] array = new int[10][];
for (int i = 0; i <10; i++)
{
   if (i==1)
    array[i] = new int[2];
   else
    array[i] = new int[1];
   array[i][0] = (i==0) ? 0 : 1
   if (i = 1)
   {
     array[i][1] = 2
   }
}

答案 1 :(得分:0)

您可以使用多维数组,如此

static void Main(string[] args)
{
    int[,] array = new int[10, 10];

    for(int i = 0; i < array.Length / 10; i++)
    {
        array[i, 0] = 1;
        if(i == 1)
        {
            array[i, 1] = 2;
        }
    }
}

<强>结果

[0,0] = 1
[0,1] = 0 ... [0,9] = 0
[1,0] = 1
[1,1] = 2

[1,2] = 0 ... [1,9] = 0
[2,0] = 1
[2,1] = 0 ... [2,9] = 0
[3,0] = 1
[3,1] = 0 ... [3,9] = 0
[4,0] = 1
[4,1] = 0 ... [4,9] = 0
[5,0] = 1
[5,1] = 0 ... [5,9] = 0
[6,0] = 1
[6,1] = 0 ... [6,9] = 0
[7,0] = 1
[7,1] = 0 ... [7,9] = 0
[8,0] = 1
[8,1] = 0 ... [8,9] = 0
[9,0] = 1
[9,1] = 0 ... [9,9] = 0

答案 2 :(得分:0)

除了你为什么需要这个问题之外,你可以这样:

编辑:抱歉,我忘了第二次隐式转换直接使用IntWithSideValue ......

public struct IntWithSideValue {
    public int Int1;
    public int? Int2;

    public IntWithSideValue(int i1)
        : this(i1, null) { }
    public IntWithSideValue(int i1, int? i2) {
        Int1 = i1;
        Int2 = i2;
    }
    //this will transform a "normal" int directly into this struct
    public static implicit operator IntWithSideValue(int IntValue) {
        return new IntWithSideValue(IntValue, null);
    }
    //This will return Int1 if you use this "directly" like an "normal" int...
    //If you'd rather use Int2 (in case of existence), use ??-operator like Int2 ?? Int1
    public static implicit operator int(IntWithSideValue iwsv) {
        return iwsv.Int1;
    }
}

然后像这样使用它:

        var MyArray=new IntWithSideValue[5];
        MyArray[0] = new IntWithSideValue(0,null);
        MyArray[1] = new IntWithSideValue(1);
        MyArray[2] = 2;
        MyArray[3] = new IntWithSideValue(3, 10);
        MyArray[4] = 4;

        var sb=new System.Text.StringBuilder();
        for(int i=0;i<5;i++){
            sb.AppendLine(string.Format("Index {0}, Int1 {1} Int2 {2} Behaves like int (+3): {3}",
                          i, MyArray[i].Int1, MyArray[i].Int2, 
                          MyArray[i] + 3)); //direct usage
        }
        var result = sb.ToString();

会产生这样的结果:

Index 0, Int1 0 Int2     Behaves like int (+3): 3
Index 1, Int1 1 Int2     Behaves like int (+3): 4
Index 2, Int1 2 Int2     Behaves like int (+3): 5
Index 3, Int1 3 Int2 10  Behaves like int (+3): 6
Index 4, Int1 4 Int2     Behaves like int (+3): 7