【问题标题】:how to add element to array [duplicate]如何将元素添加到数组[重复]
【发布时间】:2014-05-26 14:54:57
【问题描述】:

我有这些数组

int[] ivrArray = { 1, 0, 0, 0};
int[] agentsArray = { 0, 2, 0, 0 };
int[] abandonedArray = { 0, 0, 3, 0};
int[] canceledArray = { 0, 0, 0, 4};

我用过这本词典:

 Dictionary<string, int[][]> dictionary = new Dictionary<string, int[][]>
            {
                {"IVR", ivrArray.Select(_ => new[] {_}).ToArray()},
                {"Agents", agentsArray.Select(_ => new[] {_}).ToArray()},
                {"Abandoned", abandonedArray.Select(_ => new[] {_}).ToArray()},
                { "Cancelled",canceledArray.Select(_ => new[] {_}).ToArray()}
            };

改成json后的结果是:

{
  "IVR": [
    [1],
    [0],
    [0],
    [0]
  ],
  "Agents": [
    [0],
    [2],
    [0],
    [0]
  ],
  "Abandoned": [
    [0],
    [0],
    [3],
    [0]
  ],
  "Cancelled": [
    [0],
    [0],
    [0],
    [4]
  ]
}

你可以看到JSON中的每个元素都是这样的数组[[0],[0],[0],[4]]

我需要为该数组中的每个元素添加另一个值,因此结果将是:

[[1325376000000,0],[1328054400000,0],[1330560000000,0],[1333238400000,0]]

我该怎么做?

这些值对于所有四个数组都是静态的。

【问题讨论】:

  • 你不是在 2 小时前问了几乎同样的问题吗? stackoverflow.com/questions/23028526/…
  • 除此之外,真的感觉你应该创建一个具有 IVR、代理、废弃等属性的新类型。然后你可以只拥有 一个 集合。
  • 创建数组时只添加其他值:new[] {otherValue, _}
  • @SonerGönül 不,这是一个完全不同的问题
  • @sjkm 你能给我一个答案吗?

标签: c# arrays json


【解决方案1】:

这样做:

dictionary.Add("new values", new[] 
                             { 
                               new[] {123, 0}, 
                               new[] {123, 0}, 
                               new[] {123, 0}, 
                               new[] {123, 0}
                              });

【讨论】:

  • 所以我需要对ivr、agents、abandont 和canceled 这四个元素执行此操作,难道没有通用的方法吗?就像我在问题中给出的那样
【解决方案2】:

JSON 序列化器会将 List&lt;T&gt; 序列化为 JSON 数组,因此使用列表会比 数组数组 更好。

您的字典应该是Dictionary&lt;string, List&lt;List&lt;int&gt;&gt;&gt;,并且您将能够获取子列表并添加项目:

dict["some"][0].Add(0);

【讨论】:

    【解决方案3】:

    只需在创建数组时添加另一个值:new[] {otherValue, _}

    【讨论】:

      猜你喜欢
      • 2011-12-02
      • 1970-01-01
      • 2020-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-19
      • 1970-01-01
      相关资源
      最近更新 更多