问题描述
所有我想做的是正确地声明 var place
,所以一旦我到达 foreach
循环。我假设我需要在如果
语句之前声明它。这是一个正确的假设,如果是这样,我如何声明它?谢谢!连接
的
All I want to do is declare var place
correctly so it is still in scope once I get to the foreach
loop. I'm assuming I need to declare it before the if
statement for connections
. Is this a correct assumption and if so how do I declare it? Thanks!
using (var db = new DataClasses1DataContext())
{
if (connections == "Connections")
{
var place = (from v in db.pdx_aparts
where v.Latitude != null && v.Region == region && v.WD_Connect >= 1
select new
{
locName = v.Apartment_complex.Trim().Replace(@"""", ""),
latitude = v.Latitude,
longitude = v.Longitude
}).Distinct().ToArray();
}
else
{
var place = (from v in db.pdx_aparts
where v.Latitude != null && v.Region == region && ((v.WD_Connect == null) || (v.WD_Connect == 0))
select new
{
locName = v.Apartment_complex.Trim().Replace(@"""", ""),
latitude = v.Latitude,
longitude = v.Longitude
}).Distinct().ToArray();
}
foreach (var result in place)
....
推荐答案
您可以使用单个条目创建一个数组,其值稍后忽略:
You can create an array with a single entry whose value you ignore later:
// Note: names *and types* must match the ones you use later on.
var place = new[] { new { locName = "", latitude = 0.0, longitude = 0.0 } };
if (connections = "Connections")
{
// Note: not a variable declaration
place = ...;
}
else
{
place = ...;
}
这是因为每次使用匿名类型都使用具有相同名称和类型的属性,以相同的顺序,将使用相同的具体类型。
This works because every use of anonymous types using properties with the same names and types, in the same order, will use the same concrete type.
我认为最好只让代码不同它需要:
I think it would be better to make the code only differ in the parts that it needs to though:
var query = v.db.pdx_aparts.Where(v => v.Latitude != null && v.Region == region);
query = connections == "Connections"
? query.Where(v => v.WD_Connect >= 1)
: query.Where(v => v.WD_Connect == null || v.WD_Connect == 0);
var places = query.Select(v => new
{
locName = v.Apartment_complex
.Trim()
.Replace("\"", ""),
latitude = v.Latitude,
longitude = v.Longitude
})
.Distinct()
.ToArray();
这里更容易说明只有部分取决于 connections
value是处理 WD_Connect
的查询部分。
Here it's much easier to tell that the only part which depends on the connections
value is the section of the query which deals with WD_Connect
.
这篇关于将匿名类型声明为数组以保留范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!