2013-05-22 64 views
0

我正試圖獲得每個類別中最近的位置。任何人都可以幫我做到這一點?如何選擇每個類別的最近距離

var xml = new XElement("Locations", 
        locations.OrderBy(n => n.CategoryID) 
         .ThenBy(n => distance(lat, lon, (double)n.Latitude, (double)n.Longitude)) 
         .Where(n => (distance(lat, lon, (double)n.Latitude, (double)n.Longitude) <= 5)) 
         .Select(location => 
         new XElement("Location", 
          new XAttribute("CategoryID", location.CategoryID), 
          new XElement("Category", location.Category), 
          new XElement("LocationID", location.LocationID), 
          new XElement("LocationName", location.LocationName), 
          new XElement("Latitude", location.Latitude), 
          new XElement("Longitude", location.Longitude), 
          new XElement("Distance", distance(lat, lon, (double)location.Latitude, (double)location.Longitude)), 
          new XElement("Status", (location.HasManagedHours ? "Managed Hours" : "Open")) 
          ))); 

回答

1

我沒有測試過,但我會建議分組是要走的路,是這樣的:

var xml = new XElement("Locations",        
    locations 
    .GroupBy(n => n.CategoryID) 
    .SelectMany(g => g 
     .OrderBy(n => distance(lat, lon, (double)n.Latitude, (double)n.Longitude)) 
     .Take(1)) 
    .Select(location => 
     new XElement("Location", 
      new XAttribute("CategoryID", location.CategoryID), 
      new XElement("Category", location.Category), 
      new XElement("LocationID", location.LocationID), 
      new XElement("LocationName", location.LocationName), 
      new XElement("Latitude", location.Latitude), 
      new XElement("Longitude", location.Longitude), 
      new XElement("Distance", distance(lat, lon, (double)location.Latitude, (double)location.Longitude)), 
      new XElement("Status", (location.HasManagedHours ? "Managed Hours" : "Open")) 
     ))); 

更多信息,請參見Projection OperatorsGrouping Operators

+0

所以第一個選擇只是選擇最上面的一個,第二個選擇是創建元素並返回它們?你能做兩個這樣的選擇,我從來沒有嘗試過? –

+0

。首先要求一個布爾值 –

+0

本來是要Take(1),我已經更新了答案。 – mcNux