'Populating objects inside arrays in blazor

if one has the following json object

"data": {
    "userAssetLocations": [
      {
        "assets": {
          "asset_name": "KCC 240Y",
          "actual_owner": "NULL",
          "devices": [
            {
              "currentLoc": {
                "unit_id": "866795036732830",
                "fixtime": "2022-03-17T07:03:20.000+03:00",
                "local_fixtime": "2022-03-17T10:03:20.000+03:00",
                "gps_event": 1,
                "battery_level": 12
              }
            }
          ]
        }
      },
 public class CurrentLoc
    {
       
        public string? unit_id { get; set; }
        public DateTime fixtime { get; set; }
        public DateTime local_fixtime { get; set; }
        public int? gps_event { get; set; }
        public int? battery_level { get; set; }
        public object? alerts { get; set; }
        
    }

    public class Device
    {
 
       
        public CurrentLoc current { get; set; }
        public int id { get; set; }
    }

    public class Assets
    {
   
        public string asset_name { get; set; }

        public string asset_owner { get; set; }
        public List<Device> devices { get; set; }
        public int id { get; set; }
    }

    public class UserAssetLocation
    {
        public string __typename { get; set; }
        public Assets assets { get; set; }
        public int id { get; set; }
    }

and created the class below

once the graphql api is called, I am able to see the data on my blazor client, however, I am experiencing difficulties in getting a value like unit_id in the CurrentLoc object, my question would be how do you iterate using a foreach loop and be able to reach any property under currentLoc



Solution 1:[1]

if you have a list of UserAssetLocation, a simple iteration:

        //var UserAssetLocations = list of UserAssetLocation
                        :
        foreach(var userassetlocation in UserAssetLocations)
        {
            foreach(var device in userassetlocation.assets.devices)
            {
                var unitid = device.current.unit_id;
                Console.WriteLine($"unitid: {unitid} for deviceID:{device.id}");
            }
        }

you could use linq:

var search = UserAssetLocations.Select(x => x.assets.devices.Select(d => (d.id, d.current.unit_id))).ToList();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1