Linq 无法遍历返回的集合

Linq 无法遍历返回的集合,linq,entity-framework,lambda,Linq,Entity Framework,Lambda,我有以下程序,从数据库中获取数据并将其发送到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 m

我有以下程序,从数据库中获取数据并将其发送到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
,因此无法获取对象类型

如果您为Country创建了一个类,并且该方法返回IEnumerable
,那么它就可以工作了

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;
            }
public IEnumerable GetAllCountry()
{
var countries=COUNTRY.选择(c=>new
{
国家=新国家
{
ID=c.ID,
描述=c.描述,
CountryPhoneCode=c.国家电话号码,
货币=c.Currency.Currency\u符号,
}
});
foreach(国家/地区的var t)
{
Console.WriteLine(“{0}”,t.country.ID);//在这里工作,我可以在这里访问t.country.ID。。。
}
返回国;
}