2017-02-28 27 views
0

我確信這已被回答,我找不到它。總之,我有一個LINQ的聲明,我比較一GeoCoorinate與用戶輸入另一會有地理座標基地:如何捕獲在where子句中創建的Linq(方法語法)值?

var agents = db.AllAgentLocations() 
        .AsEnumerable() 
        .Where(al => al.PrimaryOffice) 
        .Where(al => (25 >= (searchCoords.GetDistanceTo(
           new GeoCoordinate 
           { 
            Latitude = double.Parse(al.Location.Latitude), 
            Longitude = double.Parse(al.Location.Longitude) 
           } 
         )/1609.34))) 
         .Select(a => a.Agent); 

查詢工作得很好,我得到一個IEnumerable的預期輸出。我想弄清楚的

(25 >= (searchCoords.GetDistanceTo(
     new GeoCoordinate 
     { 
      Latitude = double.Parse(al.Location.Latitude), 
      Longitude = double.Parse(al.Location.Longitude) 
     } 
    )/1609.34) 

我期待輸出產生的距離的方式把雙方劑(S)和距離(S)到一個IEnumerable它看起來像這樣:

public class AgentDistanceViewModel 
{ 
    public Agent Agent { get; set; } 
    public double Distance { get; set; } 
} 

回答

3

你Where子句前只需添加一個投影(選擇)來轉換輸入對象到一個新的對象,那麼你可以在WHERE子句應用到新的對象,而不是:

var agents = db.AllAgentLocations() 
    .AsEnumerable() 
    .Where(al => al.PrimaryOffice) 
    .Select(al => new AgentDistanceViewModel { 
     Agent = al.Agent, 
     Distance = searchCoords.GetDistanceTo(
      new GeoCoordinate { 
       Latitude = double.Parse(al.Location.Latitude), 
       Longitude = double.Parse(al.Location.Longitude) 
      } 
     )/1609.34 
    }) 
    .Where(dvm => 25 >= dvm.Distance) 
    // ... 

這是更有益考慮Linq查詢不是「SQL for C#」,而是作爲將變換應用到對象流的框架。您可以在任何時候,以任何順序應用投影,過濾,排序等。如果最後的結果缺少一些信息,那麼只需添加一個變換來添加它!

+0

完美,感謝您抽出寶貴的時間來解釋。這實際上有很大幫助。 –

1

之前還是可以篩選項目的值到目標類型

var agents = db.AllAgentLocations().AsEnumerable() 
       .Where(al => al.PrimaryOffice) 
       .Select(al => new AgentDistanceViewModel 
          { 
           Agent = al.Agent, 
           Distance = searchCoords.GetDistanceTo(
             new GeoCoordinate 
             { 
             Latitude = double.Parse(al.Location.Latitude), 
             Longitude = double.Parse(al.Location.Longitude) 
          })/1609.34 
          }) 
        .Where(a => a.Distance < 25);