在很短的时间内得到大家的帮助。通过重写toString方法解决了这个问题。
我有以下问题:(已解决)
public class CryptoApiResponse
{
[DeserializeAs(Name = "ticker")]
public List<CryptoAttributes> CryptoCurrency { get; set; }
public override string ToString()
{
return $"Currency:{CryptoCurrency[0].Currency} " +
$"PriceFiat:{CryptoCurrency[0].PriceFiat} " +
$"Fiat:{CryptoCurrency[0].TargetFiat}";
}
}
public class CryptoAttributes
{
[DeserializeAs(Name = "base")]
public string Currency { get; set; }
[DeserializeAs(Name = "target")]
public string TargetFiat { get; set; }
[DeserializeAs(Name = "price")]
public string PriceFiat { get; set; }
}我想要访问以下内容:
public void Display<CryptoApiResponse>(List<CryptoApiResponse> apiList)
{
if (apiList != null)
{
foreach (CryptoApiResponse cryptoCurrency in apiList)
{
Console.WriteLine(cryptoCurrency.ToString());
}
}
Console.ReadLine();
}发布于 2018-01-21 20:29:09
Console.WriteLine(obj);
// this means more or less the following
Console.WriteLine(obj.ToString());
// this means you should override the ToString() method
// or to make a custom string您正在迭代一个列表,并且在每个加密中都存在一个子列表列表。简而言之,你得到了List>。
当您对此列表进行foreach时,可能需要使用第二个foreach来迭代Sub列表中的值以访问您的属性。
foreach (var crypt in crypto)
{
foreach (var basedata in crypt.Ticker)
{
Console.WriteLine($"Currency:{basedata.Currency} Price: {basedata.Price} Target: {basedata.Target}");
}
}发布于 2018-01-21 20:35:06
如果您保留所链接的API的名称,并区分列表和单个对象名称,那么将更容易理解问题所在。这些类应该看起来像这样(注意Ticker和Tickers之间的区别
public class Crypto
{
public List<Ticker> Tickers { get; set; }
}
public class Ticker
{
public string Currency { get; set; }
public string Target { get; set; }
public string Price { get; set; }
}Display中的参数crypto (应该是cryptos)是一个列表,Tickers是一个列表,所以需要嵌套循环。您还应该从方法签名中删除Crypto参数,因为它隐藏了Crypto类
public void Display(List<Crypto> cryptos)
{
foreach (Crypto crypto in cryptos)
{
foreach (Ticker ticker in crypto.Tickers)
{
Console.WriteLine(ticker);
}
}
}或者如果您想使用partial Linq
public void Display(List<Crypto> cryptos)
{
foreach (Ticker ticker in cryptos.SelectMany(crypto => crypto.Tickers))
{
Console.WriteLine(ticker);
}
}发布于 2018-01-21 20:33:06
你能试着在循环时使用"Crypto“而不是"var”吗?我的意思是像这样做。我记得VS2015之前的版本(可能是VS2010),如果我们使用"var“,变量的类型将被视为object。
public void Display<Crypto>(List<Crypto> crypto)
{
if (crypto != null)
{
// Currency, Target and Price
foreach (***Crypto*** ticker in crypto)
{
Console.WriteLine(ticker); // ticker Type Crypo
// ticker.Ticker
}
}
Console.ReadLine();
}https://stackoverflow.com/questions/48366647
复制相似问题