C#中var的初始化
考虑下面的代码:
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()
?
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()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可能应该遵循 Jon Skeet 或 Nick Berardi 的建议,并制定一个更好的查询,但如果您确实有充分的理由这样做,那么这里是您实际问题的答案:
为了能够访问变量 ids< /em> 离开循环范围后,您必须在外部声明它。 但不能使用 var 关键字,除非在声明变量时对其进行赋值。 所以你必须显式声明类型:
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:
嗯,主要问题与使用“var”无关。 您有一个 foreach 循环,其中声明了变量,然后您尝试使用该变量从循环外部返回。 您期望该值是多少?
如果您尝试选择所有国家/地区,为什么不这样做:
迭代每个大陆的意义何在? 或者 Continents 属性中是否存在未显示的 Continents 属性未引用的国家/地区?
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:
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?
我认为您以非最佳方式使用 LINQ
然后根据这些 id 进行查找,但是我不知道您的数据模型,但如果您的内容和国家/地区表链接起来,那么执行此操作会更容易。
其中属性 Country 是基于 CountryId 值的属性。
I think that you are using LINQ in a non-optimal way
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.
Where the property Country is a property which is based on the CountryId value.