将 API 响应对象转换为列表 <T>

converting an API response object into a List<T>

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

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

我确保包含 'using System.Linq;' 指令。

这里是错误:

'ListCharacterResponse' does not contain a definition for '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;
}

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

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);

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

谢谢!

如果 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;
}