在 blazor 中填充数组内的对象

Populating objects inside arrays in blazor

如果有以下 json 个对象

"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; }
    }

并创建了下面的 class

一旦 graphql api 被调用,我就可以在我的 blazor 客户端上看到数据,但是,我在 CurrentLoc 对象中获取像 unit_id 这样的值时遇到困难,我的问题是如何使用 foreach 循环进行迭代并能够到达 currentLoc

下的任何 属性

如果你有一个 UserAssetLocation 列表,一个简单的迭代:

        //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}");
            }
        }

你可以使用 linq:

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