-1

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?

Mhd
  • 771
  • 1
  • 8
  • 15
  • I don't see a tree, here but alas. What have you tried? – Fildor Feb 10 '23 at 11:30
  • 1
    Why this is stored in this way at all? Why you don't serialize a type to json which you can deserialize and then easily modify? `dynamic data` should be a class `Data` which contains a property `Headers` and a `List Values`. Then you can easily remove the value with `ID=5658830` from the list and serialize it back to json. – Tim Schmelter Feb 10 '23 at 11:42
  • I want values and headers to be separate. In JSON data I will get [{"ID":5658830,"ENT_COMPANY1": "Training Services Llc"}] don't want this – Mhd Feb 10 '23 at 11:52
  • Then do what @TimSchmelter said. – Ralf Feb 10 '23 at 12:00
  • ok now I have List with the expected result. Now how to convert List into values and headers format string? @TimSchmelter – Mhd Feb 10 '23 at 12:09
  • Show the class (update the question) especially how the values property looks like you should have now in that class. – Ralf Feb 10 '23 at 12:19
  • Question updated. Please check – Mhd Feb 10 '23 at 12:34
  • 1
    Your expected result is not a string, yet your question (and title) is saying you want a string. If you can't hardcode your headers, then use reflection to get the properties of your type. Loop through the properties, then loop through the values, and build your desired output. – thewallrus Feb 10 '23 at 13:38

1 Answers1

0

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.

Krausladen
  • 138
  • 10