Mhd
Mhd

Reputation: 811

How to convert List<model> to string?

I have a list of data and want to convert it into string format like headers and values separated. How can I achieve this in c#?

enter image description here enter image description here

Expected Result:

dynamic data = {
  "values": [
    [
      5658830,
      "Support And Training Services Llc",
      "PAM",
      "FINNESAND"
    ],
    [
      5658831,
      "Training Services Llc",
      "Bob",
      "MCCART"
    ]
  ],
  "headers": [
    "ID",
    "ENT_COMPANY1",
    "FirstName",
    "LastName"
  ]
}

How to convert in List into above format?

Upvotes: -1

Views: 354

Answers (1)

Krausladen
Krausladen

Reputation: 148

Here's a quick snippet to answer your question, in my own code. You'll still have to propogate the list of objects with whatever it is you have. Just change "object" to the name of your model.

        List<string> listOfStrings = new List<string>();
        List<object> listOfMyModels = new List<object>();
        
        //fill your list of objects here with whatever it is you're converting to a string

        foreach(object myObject in listOfMyModels)
        {
            string json = JsonConvert.SerializeObject(myObject);
            listOfStrings.Add(json);
        }

Now you have a list of strings that represent your objects and when needed, you can use the deserialize method to read it.

Upvotes: 0

Related Questions