使用C#将List转换为数组
本文关键字:数组 转换 List 使用 | 更新日期: 2023-09-27 18:27:59
我正在尝试转换从API获取的列表,并将其转换为列表。列表确实返回了其他数据,但我有代码只返回我想要的数据(可能是错误的)
//this pulls the data
public List<AccountBalance> CorpAccounts(int CORP_KEY, string CORP_API, int USER)
{
List<AccountBalance> _CAccount = new List<AccountBalance>();
EveApi api = new EveApi(CORP_KEY, CORP_API, USER);
List<AccountBalance> caccount = api.GetCorporationAccountBalance();
foreach (var line in caccount)
{
//everyting after
string apiString = line.ToString();
string[] tokens = apiString.Split(' ');
_CAccount.Add(line);
}
return _CAccount;
}
//I am trying to convert the list to the array here
private void docorpaccounts()
{
string[] corpbal = cwaa.CorpAccounts(CORP_KEY, CORP_API, USER).ToArray();
}
有了这个代码,我得到了这个错误:
错误1无法隐式转换类型"EveAI.Live.AccountBalance[]"到"string[]"
不确定我在这里做错了什么。
您正试图将AccountBalance[]
分配给string[]
——正如错误所说。
除非您真的需要string[]
,否则应该将变量声明更改为AccountBalance[]
:
private void docorpaccounts()
{
AccountBalance[] corpbal = cwaa.CorpAccounts(CORP_KEY, CORP_API, USER).ToArray();
}
或者指定应如何将AccountBalance
转换为string
。例如使用ToString
方法:
private void docorpaccounts()
{
string[] corpbal = cwaa.CorpAccounts(CORP_KEY, CORP_API, USER)
.Select(x => x.ToString())
.ToArray();
}
或其属性之一
private void docorpaccounts()
{
string[] corpbal = cwaa.CorpAccounts(CORP_KEY, CORP_API, USER)
.Select(x => x.MyStringProperty)
.ToArray();
}
List<T>.ToArray
方法(msdn)
语法:
公用T[]ToArray()
所以,如果您有List<AccountBalance>
,那么在调用ToArray
方法时应该有AccountBalance[]
。
试试这个:
AccountBalance[] corpbal = cwaa.CorpAccounts(CORP_KEY, CORP_API, USER).ToArray();
正如@BenjaminGruenbaum在评论中提到的,更好的选择是使用var关键字(msdn):
var corpbal = cwaa.CorpAccounts(CORP_KEY, CORP_API, USER).ToArray();