c# - 将 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);
还有其他方法可以将其转换为列表吗?
谢谢!
解决方案
如果 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;
}
推荐阅读
- typescript - 量角器打字稿VScode调试
- node.js - 使用 Json 数据渲染 HTML 页面
- ansible - Ansible:删除标准输出中不需要的字符
- laravel - Laravel 路由不能通过 GET 工作,而相同的路由通过 VIEW 工作
- javascript - React - componentWillReceiveProps 条件不会呈现组件中的数据
- python - 如何在循环中启动来自不同类的对象?
- php - Eloquent 模型上的自定义过滤
- javascript - 通过 PHP 流式传输时,Safari 中的音频持续时间总是返回无穷大
- html - 并排不同尺寸的图像?
- javascript - 我的代码有什么问题?我没有收到错误消息;我没有得到任何回应