-1

I'm using the following code to merge all json objects using NewtonSoft.

 var result = input.SelectMany(d => d.Select(kvp => kvp.Value))
                    .Select((value, index) => new {index, value})
                    .ToDictionary(iv => iv.index, iv => iv.value);

However I want to change it to json array without loosing the order. Using "toArray" just adds each individual json object to json array. How do I add only the values to the json array?

the value of result is ,

{"0":"a","1":"b","2":"c","3":"d","4":"e"}

im trying to get the output to be [a,b,c,d,e] sequentially without loosing the order of the index as in the key.

  • 1
    It would be awesome if you could provide a [mcve] where the input is defined **in code** in the [mcve]. – mjwills Nov 17 '19 at 11:02

1 Answers1

2

Calling .ToDictionary() already looses order.

Without knowing the types of the variables you are processing, it is a bit difficult to provide a comprehensive answer, but you probably just want to replace .ToDictionary by .Select(iv => iv.value.something), followed by .ToArray(). This will only give you the values and preserve order.

janw
  • 8,758
  • 11
  • 40
  • 62
  • yes, but I use `iv => iv.index, iv => iv.value` to preserve the order –  Nov 17 '19 at 10:32
  • I will add the json object that Im trying to convert as json array –  Nov 17 '19 at 10:32
  • I have added the value of result –  Nov 17 '19 at 10:33
  • im trying to get the output to be [a,b,c,d,e] sequentially without loosing the order of the index as in the key. –  Nov 17 '19 at 10:35
  • So you are using `.ToDictionary()` as a means of sorting your values? In this case, replace it by `.OrderBy()`, followed by the `.Select()` and `.ToArray()` from my answer. – janw Nov 17 '19 at 10:36
  • I tried it. Unfortunately it says Type argument method can not be inferred :( could you please jot it down? –  Nov 17 '19 at 10:54
  • 1
    Could you add your input to the question, as code? This will really help providing a working solution :) – janw Nov 17 '19 at 11:10