c# - 从索引数组动态填充 mvvm 模型

标签 c# xamarin mvvm xamarin.forms xamarin.ios

GetAirports让我填写 _airports如果要取消索引,这意味着如果我使用 _airport[0] 也可以获得机场。

但是通过这个公共(public) API 链接获取机场 https://desktopapps.ryanair.com/en-gb/res/stations使用带有分配给它们的对象的索引数组。我怎样才能动态填充 _airports并在不知道实际索引名称的情况下提取它们?

public async Task<List<Airports>> GetAirports()
{
    string url = _BASEURL;
    if( _airports == null)
        _airports = await GetAsync<List<Airports>>(url);

    return _airports;
}

GetAsync 函数:

protected async Task<T> GetAsync<T>(string url)
    {
        using (HttpClient client = CreateHttpClient())
        {
            try
            {
                var json = await client.GetStringAsync(url);
                return await Task.Run(() => JsonConvert.DeserializeObject<T>(json));
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                return default(T);
            }
        }
    }

机场模型:

public class Airports
{
    public string Name { get; set; }
    public string Country { get; set; }
    public string TimeZone { get; set; }
    public string Latitude { get; set; }
    public string Longitude { get; set; }
}

来自 API

"AAL":{
    "name":"Aalborg Airport",
    "country":"DK",
    "timeZone":"DK",
    "latitude":"570535N",
    "longitude":"0095100E"
},
"AAR":{...}

最佳答案

这是一个基于从 API 返回的数据格式的解决方法。

向模型添加一个额外的属性来保存 key /代码,如 AAL

public class Airport { //<-- note the name change of the model
    public string Code { get; set; }
    public string Name { get; set; }
    public string Country { get; set; }
    public string TimeZone { get; set; }
    public string Latitude { get; set; }
    public string Longitude { get; set; }
}

下一步重构解析以使用Dictionary<string, Airport>然后提取 KeyValuePair s 返回想要的类型

public async Task<List<Airport>> GetAirportsAsync() { //<-- note the name change
    string url = _BASEURL;
    if( _airports == null) {
        var data = await GetAsync<Dictionary<string, Airport>>(url);
        _airports = data.Select(_ => {
            var code = _.Key;
            var airport = _.Value;
            airport.Code = code;
            return airport;
        }).ToList();
    }

    return _airports;
}

关于c# - 从索引数组动态填充 mvvm 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50045465/

相关文章:

c# - 使用 Regex.Replace 替换字符串中的前 16 位数字

c# - 如何使 Entity Framework 6 使用 SQL SEQUENCE 中的默认值

ios - 在不创建新的 UICollectionView 的情况下更新 UICollectionViewFlowLayout?

c# - 将数据从 fragment 发送到 Activity android C#

c# - 使用 mvvm 在 xamarin 表单中的 View 之间传递数据

c# - 在 Provider Ninject 中检索自定义绑定(bind)参数

c# - 如何检测某个设备的存在

c# - 通过 HTTPClient 使用 c# CLR 存储过程调用 Web API 2 方法

c# - 为什么我的 ListView 没有绑定(bind)到 ItemSsource?

ajax - Knockout JS - 使用 AJAX 调用更新 viewModel