首页 > 解决方案 > 将 API 响应对象转换为 List

问题描述

我正在尝试从 3rd 方 API 获得响应并将其转换为列表。

我在下面的行中收到此错误,我将结果分配给“returnValue”。

我确保包括“使用 System.Linq;” 指示。

这是错误:

“ListCharacterResponse”不包含“ToList”的定义

public List<T> RetrieveCharacterListFromApi<T>(Guid gameId)
{
    List<T> returnValue = default(List<T>);
    var getCharacterResponse = GetCharacters(gameId);
    var results = getCharacterResponse.Result;
    // 'ListCharacterResponse' does not contain a definition for 'ToList'.
    returnValue = results.ToList<T>();

    return returnValue;
}

这是我连接到返回 ListCharacterResponse对象的第 3 方 API 的地方:

public async Task<ListCharacterResponse> GetCharacters(Guid gameId)
{
    ListCharacterResponse response;
    response = await charMgr.GetCharactersListAsync(gameId);
    return response;
}

我在 .net 控制器中像这样使用 RetrieveCharacterListFromApi:

Guid gameId;
var characters = new List<Character>();
characters = API.RetrieveCharacterListFromApi<Character>(gameId);

还有其他方法可以将其转换为列表吗?

谢谢!

标签: c#asp.net-core-2.0

解决方案


如果 API 调用的结果是Character格式的,那么你基本上就在那里。而不是.ToList<T>()你可以:

public List<T> RetrieveCharacterListFromApi<T>(Guid gameId)
{
    // List<T> returnValue = default(List<T>);
    var getCharacterResponse = GetCharacters(gameId);
    var results = getCharacterResponse.Result;
    // 'ListCharacterResponse' does not contain a definition for 'ToList'.
    List<T> returnValue = new List<T>(results);

    return returnValue;
}

或者,如果您需要迭代:

public List<T> RetrieveCharacterListFromApi<T>(Guid gameId)
{
    List<T> returnValue = default(List<T>);
    var getCharacterResponse = GetCharacters(gameId);
    var results = getCharacterResponse.Result;
    // 'ListCharacterResponse' does not contain a definition for 'ToList'.
    foreach(Character character in results)
        returnValue.Add(character);

    return returnValue;
}

推荐阅读