简体   繁体   中英

Initialization of var in C#

Consider below code:

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)
{

}

How can I initialize the var ids such that I can use it to call GetPopulation() ?

Well, the main problem has nothing to do with using "var". You've got a foreach loop with the variable declared inside it, and then you're trying to return from outside the loop using that variable. What would you expect the value to be?

If you're trying to select all the countries, why don't you just do this:

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

What's the point of iterating through each of the continents? Or are there countries in the continentTable which aren't referenced by the Continents property which you haven't shown?

I think that you are using LINQ in a non-optimal way

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

And then look up based on those ids, however I don't know your datamodel but if your content and country table are linked it would be easier to do this.

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

Where the property Country is a property which is based on the CountryId value.

You should probably follow Jon Skeet's or Nick Berardi's advice and just formulate a better query, but if you actually have a good reason for doing this, here is the answer to your actual question:

To be able to access the variable ids after having left the scope of the loop, you have to declare it outside. But you cannot use the var -keyword unless you assign to the variable when you declare it. So you have to declare the type explicitly:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM