0

I'm trying to serialize an Array to use with a Google Chart lib.

var data = google.visualization.arrayToDataTable([
      ['Task', 'Hours per Day'],
      ['Work',     11],
      ['Eat',      2],
      ['Commute',  2],
      ['Watch TV', 2],
      ['Sleep',    7]
    ]);

But when I tried to use KeyValuePair I can only use two types of data to my all collection and in the example above, the first Row has two strings. How can I render this information and convert to array to match the JS data ?

1
  • that exact data is shown in the documentation - you're doing it wrong - look for the text The following example creates a new, empty DataTable and then populates it manually with the same data as above and you'll see basically what you're trying to do Commented Sep 5, 2019 at 23:40

1 Answer 1

1

If you have data which is not strongly typed (the value can either be a string or an integer), you can always use generic objects. 3 different c# examples:

List of Key/Value pairs:

var data = new List<KeyValuePair<string, object>>(){
     new KeyValuePair<string,object>("Task", "Hours per Day"),
     new KeyValuePair<string,object>("Work", 11) // etc...            
     };

2D Object array

var data = new object[,] {
                {"Task", "Hours per Day"},
                {"Work", 11} // etc...            
                };

Dictionary

  var data = new Dictionary<string, object>(){
                 {"Task", "Hours per Day"},
                {"Work", 11} // etc...            
            };

There are many ways to do what you want, depending on how you want to parse / convert / deserialize your data.

Sign up to request clarification or add additional context in comments.

3 Comments

I think the first example will do, I have a list of items that I need to put into an array and convert to Json. I'll try now
2D Object array but I have a list, how to insert the items into this object[,]
Arrays usually work best when you know the exact size of your data set. You could also explore the ToArray method. If you want to manipulate, add or remove data and don't know your set size up front, using a list or dictionary may be a better option for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.