未能遍历返回的集合



我有下面的程序,它从DB中获取数据并将其发送到Main。我可以在函数中迭代结果,但不能在Main中迭代。程序如下:

  void Main()
{
    var data = GetAllCountry();
//  foreach( var t in data)
//  {
//    Console.WriteLine("{0}", t.country.ID); //fails here; says country not found
//  }
}
// Define other methods and classes here
  public IEnumerable GetAllCountry()
        {
                var countries = COUNTRY.Select(c => new
                {
                    country = new
                    {
                        ID = c.ID,
                        Description = c.DESCRIPTION,
                        CountryPhoneCode = c.COUNTRY_PHONE_CODE,
                        Currency = c.CURRENCY.CURRENCY_SYMBOL,
                    }
                });
                foreach( var t in countries)
                {
                  Console.WriteLine("{0}", t.country.ID);//works here and I am able to access t.country.ID here...
                }
                return countries;
            }

这怎么了?需要进行哪些修改?

我相信,由于您返回的是IEnumerable而不是IEnumerable<T>,因此无法获取对象类型。

如果您为Country创建一个类,并且该方法返回IEnumerable <Country>,那么它将在中工作

public IEnumerable<Country> GetAllCountry()
        {
                var countries = COUNTRY.Select(c => new
                {
                    country = new Country
                    {
                        ID = c.ID,
                        Description = c.DESCRIPTION,
                        CountryPhoneCode = c.COUNTRY_PHONE_CODE,
                        Currency = c.CURRENCY.CURRENCY_SYMBOL,
                    }
                });
                foreach( var t in countries)
                {
                  Console.WriteLine("{0}", t.country.ID);//works here and I am able to access t.country.ID here...
                }
                return countries;
            }

相关内容

  • 没有找到相关文章

最新更新