简体   繁体   中英

c# how to change array to array or arrays

I have this code:

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 },
                { "Agents", agentsArray },
                { "Abandoned", abandonedArray },
                { "Cancelled", canceledArray },    
            };

The output is

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

Is there anyway so the output will be like this:

"Cancelled":[
   [0],
   [0],
   [0],
   [4]
]

So each element is array of one element

You can re-project your arrays to a Dictionary<string, int[][]> like so:

 var 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()}
    };

(and I guess if you didn't want the local vars, then

 ...
   {"IVR", new [] { 1, 0, 0, 0 }.Select(_ => new[] {_}).ToArray()},
 ...

you can do like this using Jagged Arrays concept:

for example:

int[] list1 = new int[4] { 1, 2, 3, 4};
int[] list2 = new int[4] { 5, 6, 7, 8};
int[] list3 = new int[4] { 1, 3, 2, 1 };
int[] list4 = new int[4] { 5, 4, 3, 2 };

int[][] lists = new int[][] {  list1 ,  list2 ,  list3 ,  list4  };

and in dictionary:

 Dictionary<string, int[][]> items= new Dictionary<string, int[][]>;

here is MSDN documentation:

http://msdn.microsoft.com/en-us/library/2s05feca.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM