简体   繁体   中英

Creating single Array of objects from multiple array objects in c#

I have a web API response like below and I need to move all objects into a single array in C# ASP.NET

[
   [
      {
         "id":23,
         "name":"John",
         "email":"John@domain.com",
         "appointment_date":"tomorrow",
         "appointment_category":3,
         "time":"morning"
      },
      {
         "id":35,
         "name":"John",
         "email":"John@domain.com",
         "appointment_date":"tomorrow",
         "appointment_category":4,
         "time":"afternoon"
      }
   ],
   [
      {
         "id":17,
         "name":"Alex",
         "email":"Alex @domain.com",
         "appointment_date":"tomorrow",
         "appointment_category":3,
         "time":"morning"
      }
   ],
   [
      {
         "id":22,
         "name":"Bob",
         "email":"Bob@domain.com",
         "appointment_date":"tomorrow",
         "appointment_category":5,
         "time":"morning"
      }
   ]
]

I want to move all objects into single array. Like below

[
   {
      "id":23,
      "name":"John",
      "email":"John@domain.com",
      "appointment_date":"tomorrow",
      "appointment_category":3,
      "time":"morning"
   },
   {
      "id":17,
      "name":"John",
      "email":"John@domain.com",
      "appointment_date":"tomorrow",
      "appointment_category":3,
      "time":"morning"
   },
   {
      "id":17,
      "name":"John",
      "email":"John@domain.com",
      "appointment_date":"tomorrow",
      "appointment_category":3,
      "time":"morning"
   }
]

Please help me Thank u

Not sure if you have deserialized the json already. But you can do it like this. Create 2 classes and deserialize with Newtonsoft.Json. Then use Linq with SelectMany to get a list of single object.

//deseralize the json
var list1 = JsonConvert.DeserializeObject<List<List<Class2>>>(json);

//select all the nested items
var list2 = list1.SelectMany(x => x).ToList();

The classes

public class Class1
{
    public List<Class1> list { get; set; }
}


public class Class2
{
    public int id { get; set; }
    public string name { get; set; }
    public string email { get; set; }
}

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