如何通过IEnumerable <ExchangeRate>函数返回数据

时间:2019-09-08 11:12:53

标签: c# .net ienumerable

我有一个函数Ge​​tExchangeRates,需要返回IEnumerable。我不知道该怎么做。我只能在控制台中写入结果并返回NullExchangeRate是一个具有SourceCurrency / TargetCurrency = Value的类,仅具有getters(immutable)和构造函数,返回tostring() {SourceCurrency}/{TargetCurrency}={Value}"; 并且主程序类将新的[]货币集创建为IEnum。我主要构造它并调用:

var provider = new ExchangeRateProvider();
var rates = provider.GetExchangeRates(currencies)

然后循环遍历费率并打印出来。如何将源代码中的逻辑正确传递给Main函数?

public IEnumerable<ExchangeRate> GetExchangeRates(IEnumerable<Currency> currencies)
        {
            var xmldoc = new XmlDocument();
            xmldoc.Load(@"http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");

            XmlNodeList nodes = xmldoc.SelectNodes("//*[@currency]");

            if (nodes != null)
            {
                foreach (XmlNode node in nodes)
                {
                    var rate = new ExchangeRate()
                    {
                        SourceCurrency = new Currency("EUR"),
                        TargetCurrency = new Currency(node.Attributes["currency"].Value),
                        Value = (Decimal.Parse(node.Attributes["rate"].Value, NumberStyles.Any,
                            new CultureInfo("en-Us")))
                    };
                    Console.WriteLine(rate);
                }
            }
            return null;
        }

    }

1 个答案:

答案 0 :(得分:0)

您可以在此处使用yield return关键字。例如,

yield return rate;

完整代码

public IEnumerable<ExchangeRate> GetExchangeRates(IEnumerable<Currency> currencies)
{
            var xmldoc = new XmlDocument();
            xmldoc.Load(@"http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");

            XmlNodeList nodes = xmldoc.SelectNodes("//*[@currency]");

            if (nodes != null)
            {
                foreach (XmlNode node in nodes)
                {
                    var rate = new ExchangeRate()
                    {
                        SourceCurrency = new Currency("EUR"),
                        TargetCurrency = new Currency(node.Attributes["currency"].Value),
                        Value = (Decimal.Parse(node.Attributes["rate"].Value, NumberStyles.Any,
                            new CultureInfo("en-Us")))
                    };
                    // ADDED YIELD RETURN  
                    yield return rate;
                }
            }
        }

    }

yield return关键字将一次返回每个元素。您可以在Yield关键字here中阅读更多内容