【问题标题】:Initialization of var in C#C#中var的初始化
【发布时间】:2010-10-03 19:54:34
【问题描述】:

考虑下面的代码:

public IEnumerable <Country> ListPopulation()
{
    foreach(var continent in Continents)
    {
        var ids = context.continentTable
                   .where(y=>y.Name == continent.name)
                   .select(x=>x.countryId);

    }

    return GetPopulation(ids);// ids is not available here
}

Public IEnumerable<Country>GetPopulation(IQueryable<int> idnumbers)
{

}

如何初始化 var ids 以便我可以使用它来调用 GetPopulation()

【问题讨论】:

    标签: c# winforms linq var


    【解决方案1】:

    嗯,主要问题与使用“var”无关。您有一个 foreach 循环,其中声明了变量,然后您尝试使用该变量从 outside 循环返回。您希望该值是多少?

    如果您想选择所有个国家,为什么不这样做:

    public IEnumerable <Country> ListPopulation()
    {
        return GetPopulation(context.continentTable.Select(x => x.countryId));
    }
    

    遍历每个大陆有什么意义?或者您未显示的 Continents 属性未引用 continents 中的国家/地区?

    【讨论】:

      【解决方案2】:

      我认为您以非最佳方式使用 LINQ

      var ids = from c in context.continetTable
                select c.countryId
      

      然后根据这些 id 进行查找,但是我不知道您的数据模型,但如果您的内容和国家/地区表是链接的,这样做会更容易。

      public IEnumerable <Country> ListPopulation()
      {
          return from c in context.contentTable
                 select c.Country;
      }
      

      属性 Country 是基于 CountryId 值的属性。

      【讨论】:

        【解决方案3】:

        您可能应该遵循 Jon Skeet 或 Nick Berardi 的建议并制定更好的查询,但如果您确实有这样做的充分理由,这里是您实际问题的答案:

        为了能够在离开循环范围后访问变量ids,你必须在外面声明它。但是你不能使用 var-keyword,除非你在声明它时给它赋值。所以你必须明确声明类型:

        public IEnumerable <Country> ListPopulation()
        {
          IQueryable<Country> ids;
          foreach(var continent in Continents)
          {
            var ids = context.continentTable
                      .Where(y=>y.Name == continent.Name)
                      .Select(x=>x.countryId);
          }
        
          return GetPopulation(ids);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-04-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-11-03
          相关资源
          最近更新 更多