正确地将匿名类型声明为数组以保持范围

Sea*_*_05 3 c# linq c#-4.0

我想做的就是var place正确声明,这样一旦我进入foreach循环,它仍然在范围内.我假设我需要之前声明它if的声明connections.这是一个正确的假设,如果是这样,我该如何申报?谢谢!

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)
            ....
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 7

您可以创建一个包含单个条目的数组,其值稍后会被忽略:

// 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 = ...;
}
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为每次使用具有相同名称和类型的属性的匿名类型(按相同顺序)将使用相同的具体类型.

我认为这将是更明智的代码在它需要尽管部分不同:

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();
Run Code Online (Sandbox Code Playgroud)

在这里,更容易分辨出依赖于值的唯一部分connections是查询的部分WD_Connect.