tags:

views:

469

answers:

3
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?
+5  A: 

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?

Jon Skeet
+2  A: 

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.

Nick Berardi
+2  A: 

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