无法迭代返回的集合

时间:2014-04-16 05:51:21

标签: linq entity-framework lambda

我有以下程序从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;
            }

这有什么问题?什么是必要的修改?

1 个答案:

答案 0 :(得分:1)

我相信当你返回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;
            }